繁体   English   中英

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

[英]Optimize Python Code to read various inputs as time limit exceeded

下面是我的 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

Output(与操作码相同)

4
3
9

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM