输入大值时列表索引超出范围错误

时间:2019-07-05 18:38:43

标签: python-3.x

我是一个初学者,所以请允许我接受。 索引仅迭代uptill n(仅6),因此id在列表大小中看不到任何问题。 当给出k的较小值时,代码可以正常工作。

输入: 1个 6 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

错误:

Traceback (most recent call last):
  File "practice.py", line 34, in <module>
    sum1 += abs(l[j]-prev1)
IndexError: list index out of range


# t is for testcases that re being taken
#Basically we are given n buckets where we hwve to give k chocolates in such a way that sum over i=0 
# to n-1 abs(Ai-Ai+1) where Ai is the no of chocolates for 
# ith bucket now this array is permuted in such a way that the the sum of adjacent differences becomes maximum We have to ouput the newsum. So what i am basically doing is bruteforcing it.
t = int(input())
while t>0:
    t -= 1
    n = int(input())
    k = int(input())
    x = k - k%n
    l = []
    x = x/n
    rem = k%n
    for i in range(1,n+1):
        l.append(int(x))
    #print(rem)
    i = 0
    while rem>0:
        rem-=1
        l[i] += 1
        i+=1
    l.sort()
    #print(l)
    sum1 =0
    sum1 += abs(l[n-1] - l[0])
    #print(sum)
    i = 1
    j = n-2
    prev1 = l[0]
    check1 = False
    while j > i:
        if check1:
            sum1 += abs(l[i]-prev1)
            prev1 = l[i]
            i+=1
            check1= False
        else:
            sum1 += abs(l[j]-prev1)
            prev1 = l[j]
            j+=1
            check1 = True
    #print(sum1)
    if n%2!=0 :
        if check1:
            sum1 += abs(l[i]-prev1)
        else:
            sum1 += abs(l[j]-prev1)

    #print(sum1)
    sum2 =0
    sum2 += abs(l[n-1] - l[0])
    i = 1
    j = n-2
    prev2 = l[n-1]
    check2 = True
    while j > i:
        if check2:
            sum2 += abs(l[i]-prev2)
            prev2 = l[i]
            i+=1
            check2 = False
        else:
            sum2 += abs(l[j]-prev2)
            prev2 = l[j]
            j+=1
            check2 = True
    #print(l)
    if n%2!=0 :
        if check2:
            sum2 += abs(l[i]-prev2)
        else:
            sum2 += abs(l[j]-prev2)
    print(max(sum1,sum2))

0 个答案:

没有答案