Python循环返回错误的答案,我不明白为什么

时间:2014-11-29 13:40:49

标签: python algorithm list

这是我的代码:

def readTogether(path):
    ins = open(path, "r")
    array = []  # Filtered result
    for line in ins:
        line = line.replace('\n', '')  # Remove empty lines
        while '  ' in line:
            line = line.replace('  ', ' ')  # Remove white space
        line = line.strip()
        line = line.split(' ')
        for elem in line:
            # Make sure each element is entered as integer
            array.append(int(elem))
    ins.close()
    return array

mylist = readTogether('B:\Desktop\input.txt') # http://pastebin.com/rDfYCgxP
someint = 0

# n is every number from 0 to the lenght of mylist
for n in range(0, len(mylist)):
    # for each "letter" in the n object of mylist (converted to a string)
    for x in str(mylist[n]):
        # for how many "letters" are in mylist[n]
        for y in range(0, len(str(mylist[n]))):
            someint += ((int(x) * (int(y) + 1)))
    print(someint, end=' ')
    someint = 0

这个想法是取每个整数并将数字*位置(数字)加在一起。例如,1776将为1*1 + 7*2 + 7*3 + 6*4 = 60

预期结果是:

13 8 23 81 8 5 0 122 175 203 60 94 210 9 87 66 28 16 21 6 4 0 36 60 36 43 94 42 53 96 12 170 99 141 98 25 96 158 13

实际结果:

27 18 45 375 36 5 0 936 1440 1620 210 390 1512 15 567 220 66 27 36 18 4 0 170 270 120 108 435 150 345 728 36 1485 525 1575 728 60 405 1665 150 405 1665 21

感谢任何帮助,因为我是Python的新手

2 个答案:

答案 0 :(得分:0)

我认为你需要同时循环x和y,例如改变:

 for x in str(mylist[n]):
    # for how many "letters" are in mylist[n]
    for y in range(0, len(str(mylist[n]))):
        someint += ((int(x) * (int(y) + 1)))

 for y,x in enumerate(str(mylist[n])):
      someint += ((int(x) * (y + 1)))

您当前的代码循环遍历每个数字x,然后为每个数字添加该数字* 1,然后是该数字* 2等,其中您只想在总和中包含每个数字。

答案 1 :(得分:0)

这是一个枚举内置函数的例子:

mylist = [['1', '7', '7', '6']] # http://pastebin.com/rDfYCgxP
someint = 0

# n is every number from 0 to the lenght of mylist
for value in mylist:
    someint = 0
    for i, number in enumerate(value, start=1):
        someint += i * int(number)
    print someint

枚举是做什么的?它返回一个枚举对象,一个元组列表,其中第一个值是索引,第二个值是给定列表中的值,例如:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

有关枚举的详细信息,请访问documentation page