优化Python代码,以便在超过时间限制时读取各种输入
下面是我的python代码,我希望能够针对不同的输入优化我的代码,并通过我为当前代码不断得到的时间限制错误。一些样本输入用于3个案例n,每个案例空间将有一条线分开 我尝试过创建不同的获取输入的方法,即使是对于大值的输入也是如此,但对于不同的测试用例,我无法通过时间限制错误。如果有人能告诉我代码的位置,这会减慢这个过程,这将非常有帮助优化Python代码,以便在超过时间限制时读取各种输入,python,if-statement,while-loop,time-complexity,Python,If Statement,While Loop,Time Complexity,下面是我的python代码,我希望能够针对不同的输入优化我的代码,并通过我为当前代码不断得到的时间限制错误。一些样本输入用于3个案例n,每个案例空间将有一条线分开 我尝试过创建不同的获取输入的方法,即使是对于大值的输入也是如此,但对于不同的测试用例,我无法通过时间限制错误。如果有人能告诉我代码的位置,这会减慢这个过程,这将非常有帮助 Sample tests: 3 3 2 1 1 2 1 1 1 5 2 1 1 n = int(input()) if 1<= n <= 1
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)
样本测试:
3.
3 2 1 1
2 1 1 1
5 2 1 1
n=int(输入())
如果1以上代码可以改进如下。
注意:这些条件不是必需的,因为它们通常用于提醒您必须处理的值的范围
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))
测试
输入
输出(与OP代码相同)
您如何知道问题在于读取输入的时间与处理的时间?例如,您有一个while循环,即whilei来检查问题是否在读取输入,然后保留输入,但删除处理代码,让它只输出任何值(例如0)。如果系统随后报告您的答案有误,而不是超过了时间限制,那么您就知道您的处理时间太长了。印刷货币的初始速度为P美元/天,每间隔d天,他们就会增加Q美元的产量。例如,在d天之后,费率为每天P+Q美元,在2d天之后,费率为每天P+2Q美元,依此类推。输出他们在给定时间段内能够打印的金额。我实际上相信这与你提到的循环有关,我认为对于较大的测试值,需要更长的时间。@brian012——试试我发布的解决方案,它可以不循环地计算总金额。
3
3 2 1 1
2 1 1 1
5 2 1 1
4
3
9