2017-11-25 230 views
2

对于每个数字,它必须将该数字乘以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() 
+0

请修复您的indenta并且发布*整个*代码,例如'size'是什么...... –

+0

你的代码说“检查行的长度是否为10”,但你的检查是“size == 11”。 '1-9'只有9位数字。你期望输入行看起来像什么?该操作是否仅适用于前9位数字?你在做ISBN验证吗? –

+0

@PatrickHaugh是的,我正在做ISBN验证。我把大小== 11,因为由于某种原因大小== 10不起作用。我正在通过乘以前9个数字来验证校验位,然后确保总和(261)可以被11整除。然后我验证校验位8被选中,因为261在253和264之间(11的倍数)和261是8超过253. –

回答

1
from itertools import cycle 

n = '013149498' 

print(sum(int(a)*b for a, b in zip(n, cycle(range(1, 10))))) 

在这里,我们使用range(1, 10)从1到9。然后,我们传递给itertools.cycle占输入字符串长度超过9个字符得到的整数。然后我们使用zip将输入字符串的数字与来自range的整数进行配对。对于每一对,我们将这个数字转换为一个整数,然后将这两个数字相乘。最后,我们总结产品。

编辑:

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) 

值得一提的是10位的ISBN书号标准似乎follow a different standard计算校验位。要改变你的代码遵循这一标准,你会替代range(10, 1, -1)rangevalidate

2

一个one-liner

我不知道是什么size,就是要在你的代码已经发布,所以我有将它从我的答案中删除,因为我没有看到它对问题的必要性。

这将通过每一行并生成digitssum,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