codeabbey:列表索引超出范围

时间:2016-02-16 16:59:54

标签: python

以下是问题: 让我们计算数字之和,如前所述,但将每个数字乘以其位置(从左边开始,从1开始)。例如,给定值1776,我们计算这样的加权数字总和(我们称之为" wsd")为:

wsd(1776)= 1 * 1 + 7 * 2 + 7 * 3 + 6 * 4 = 60

这是我的代码:

digitlist = []
numlist = []
def splitdigit(number):
    numlist = []
    digitlist = []
    numlist.append(number)
    while number >= 1:
        number = number/10
        numlist.append(number)
    del numlist[-1]
    for ele in numlist:
        digitlist.append(ele%10)
    return digitlist
# digit part

# test if the split digit work here:
# print (splitdigit(1234))  it works
times = int(input())
raw = raw_input()
string = raw.split()
nlist = []
outbox = []
rout = 0
res = 0
n = 0


for item in string:
    nlist.append(int(item))
# print (nlist) [it worked]
for element in nlist:
    # check for split method : checked
    # formula to make the digit work: n = len(out) | while(n>1): n=n-1 
    # rout=out[-n]*n res=res+rout(res=0)
    n = len(splitdigit(element))
    print (n)
    res = 0
    while n >= 1:
        rout = (splitdigit(element)[(n*(-1))]) * n     # I HAVEN"T CHECK THIS FORMULA OUT !!!
        res = res + rout
        n = n + 1
    outbox.append(res)
    print (outbox)
print(" ".join(str(x) for x in outbox))

这是我的跑步错误:

> 3
9 15 1776
1
Traceback (most recent call last):
  File "13.py", line 39, in <module>
    rout = splitdigit(element)[(n*(-1))] * n     # I HAVEN"T CHECK THIS FORMULA OUT !!!
IndexError: list index out of range

我在交互式python中检查过它。我想我不是要求一个超出范围的项目,但它给了我这个错误。我希望有人可以帮助我。谢谢你,爱你们。

1 个答案:

答案 0 :(得分:2)

你的想法太复杂了。

def wsd(number):
    digits = [int(i) for i in str(number)]
    result = 0
    for index, value in enumerate(digits):
        result += (index + 1) * value
    return result

print(wsd(1776))

输出:

60