我似乎不能确保python的取模函数工作正常,我尝试了各种数字,但似乎无法得到正确的划分。
ISBN号
print """
Welcome to the ISBN checker,
To use this program you will enter a 10 digit number to be converted to an International Standard Book Number
"""
ISBNNo = raw_input("please enter a ten digit number of choice")
counter = 11 #Set the counter to 11 as we multiply by 11 first
acc = 0 #Set the accumulator to 0开始循环,将字符串中的每个数字乘以描述计数器。我们需要将数字视为字符串,以获得每个位置
for i in ISBNNo:
print str(i) + " * " + str(counter)
acc = acc + (int(i) * counter) #cast value a integer and multiply by counter
counter -= 1 #decrement counter
print "Total = " + str(acc) 模数除以11 (除以余数
acc = acc % 11
print "Mod by 11 = " + str(acc)从11开始
acc = 11 - acc
print "subtract the remainder from 9 = " + str(acc)与字符串连接
ISBNNo = ISBNNo + str(acc)
print "ISBN Number including check digit is: " + ISBNNo发布于 2013-04-22 01:26:04
您的代码大部分都是正确的,除了一些问题:
1)如果ISBN,您正在尝试计算校验和(最后一位)。这意味着您应该只考虑9位数:
ISBNNo = raw_input("please enter a ten digit number of choice")
assert len(ISBNNo) == 10, "ten digit ISBN number is expected"
# ...
for i in ISBNNo[0:9]: # iterate only over positions 0..9
# ...2)这里还应该有一个特例:
ISBNNo = ISBNNo + str(acc)
print "ISBN Number including check digit is: " + ISBNNo您正在进行模11运算,因此acc可以等于10。ISBN要求使用"X“作为本例中的最后一个”数字“,可以写成:
ISBNNo = ISBNNo + (str(acc) if acc < 10 else 'X')以下是修复后的代码,其中包含示例number from Wikipedia:http://ideone.com/DaWl6y
回应评论
>>> 255 // 11 # Floor division (rounded down)
23
>>> 255 - (255//11)*11 # Remainder (manually)
2
>>> 255 % 11 # Remainder (operator %)
2(注意:我使用的是//,它代表地板分割。在Python2中,您也可以简单地使用/,因为您要除以整数。在Python3中,/始终是真除法,而//是地板除法。)
https://stackoverflow.com/questions/16133897
复制相似问题