通过增加值

时间:2017-11-25 20:57:21

标签: python-3.x for-loop if-statement range multiplying

对于每个数字,它必须将该数字乘以19。然后将所有这些值加在一起。

例如,如果文件的一行上的数字是013149498,则应为:

0*1 + 1*2 + 3*3 + 1*4 + 4*5 + 9*6 + 4*7 + 9*8 + 8*9

现在我将所有数字乘以2

def main():
    # Open the isbns.txt file for reading.
    isbn_file = open('isbns.txt', 'r')

    print ('Here are the ISBNs')

    # Get the values from the file, multiply each by 0 to 9, then sum.
    for line in isbn_file:
        # Check if the length of the line is 10.
        size = len(line)
        print('ISBN:', size)
        if size == 11:
            for number in range(0,9):
                maths = number * 2
                print(number, maths, sep="...")


        else:
            print('ISBN invalid:', line)



    # Close the file.
    isbn_file.close()


# Call the main function.
main()

2 个答案:

答案 0 :(得分:2)

A one-liner

我不确定您发布的代码中的size是什么意思,所以我已将其从我的答案中删除,因为我认为这不是问题所必需的。

现在,这将遍历每一行,并在sum中生成digits line乘以position。此值将分配给变量 - sm - 然后printed分配给每个line进行测试。

isbn_file = open('isbns.txt', 'r')

for line in isbn_file:
    sm = sum((i+1) * int(d) for i, d in enumerate(line))
    print(sm)

显然,我无法访问isbns.txt,所以我刚刚在解释器中对one-liner进行了测试,并在示例中给出了示例:

>>> line = "013149498"
>>> sm = sum((i+1) * int(d) for i, d in enumerate(line))
>>> sm
261

似乎工作正常,因为我们可以将其与手动计算结果进行比较:

>>> 0 * 1 + 1 * 2 + 3 * 3 + 1 * 4 + 4 * 5 + 9 * 6 + 4 * 7 + 9 * 8 + 8 * 9
261

答案 1 :(得分:1)

Convert.toInt32(TextBox1.Text)

在这里,我们使用from itertools import cycle n = '013149498' print(sum(int(a)*b for a, b in zip(n, cycle(range(1, 10))))) 来获取从1到9的整数。然后我们将其传递给itertools.cycle以考虑长度超过9个字符的输入字符串。然后我们使用range(1, 10)将输入字符串的数字与zip中的整数配对。对于这些对中的每一对,我们将数字转换为整数,然后将两者相乘。最后,我们总结产品。

编辑:

range

值得注意的是,10位ISBN的ISBN标准似乎follow a different standard用于计算校验位。要将代码更改为遵循该标准,您可以将def validate(isbn): # here we split the last character off, naming it check. The rest go into a list, first *first, check = isbn potential = sum(int(a)*b for a, b in zip(first, range(1, 10))) # ISBN uses X for a check digit of 10 if check in 'xX': check = 10 else: check = int(check) # % is the modulo operator. return potential%11 == check #Use a context manager to simplify file handling isbns = [] with open('isbns.txt', 'r') as isbn_file: for line in isbn_file: # get rid of leading/trailing whitespace. This was why you had to check size == 11 line = line.strip() if len(line) == 10 and validate(line): # save the valid isbns isbns.append(line) else: print('Invalid ISBN:', line) 替换为range(10, 1, -1)

中的range