优化Python代码以在超过时间限制时读取各种输入



下面是我的python代码,我希望能够针对不同的输入优化我的代码,并通过我当前代码的时间限制错误。一些样本输入是针对3种情况n的,每个情况都有一条线,这样空间就分开了

我尝试过创建不同的获取输入的方法,即使是对于大值的输入,但对于不同的测试用例,我无法通过时间限制错误。如果有人能告诉我我的代码在哪里,这将减缓这个过程,这将非常有助于

Sample tests:
3
3 2 1 1
2 1 1 1
5 2 1 1
n = int(input())
if 1<= n <= 100000:
counter = 0
while counter < n:
i = 1
a = list(map(int, input().split(' ')))
D = a[0]
d = a[1]
P = a[2]
Q = a[3]
if (1 <= d <= D <= 1000000) and d <= D <= 100:
if 1 <= P and Q <= 1000000:
days = 1
while i <= D:
if i % d == 0:
if days == 1:
Production = P + Q
Total_money = d*P
days+=1
elif days > 1:
Total_money+= Production*d
days+= 1
elif i%d == 1 and i == D:
if days <= 2:
Total_money+= Production
else:
Total_money+= Production + Q
i+= 1
counter+= 1
print(Total_money)

上面的代码可以改进如下。注意:条件语句不是必需的,因为它们通常是用来提醒您必须处理的值的范围。

def calc_total_money(D, d, P, Q):
'''
Calculates the total money 
The intervals are made up of:
Days
[   d days   |   d days   |  d days |  .... | d days | r days]
Amounts per Day
[P           |  P+Q       | P + 2*Q | P + 3*Q ...             ]
'''
intervals = D // d                    # Number of whole intervals  of d days
r = D - d*intervals                   # Number of days in last interval (i.e. partial interval)
if intervals == 0:
# No whole intervals
return P*r
else:
# intervals = number of intervals of d days (i.e. whole intervals)
# Amount in whole intervals are:
# P, P+Q, P + 2*Q, P + 3*Q, ... P + (intervals-1)*Q
# This equals: P*intervals + Q*intervals*(intervals - 1)//2
# Since each interval is d days we have amount from whole interval of:
# amount_whole_intervals = (P*intervals + Q*intervals*(intervals - 1)//2)*d
#
# Amount per day in last partial interval:
#  P + intervals*Q
# There are r days in last partial interval, so amount in last partial interval is:
# last_partial_amount = (P + intervals*Q)*r
#
# Total = amount_whole_intervals + last_partial_amount
return  (P*intervals + Q*intervals*(intervals - 1)//2)*d + (P + intervals*Q)*r

for _ in range(int(input())):
D, d, P, Q = map(int, input().split(' '))
print(calc_total_money(D, d, P, Q))

测试

输入

3
3 2 1 1
2 1 1 1
5 2 1 1

输出(与OP代码相同(

4
3
9

最新更新