2017-11-25 238 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