Modulo处理不正确

时间:2013-04-21 17:10:36

标签: python python-2.7

我似乎无法确保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)                   

Mod by 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

1 个答案:

答案 0 :(得分:0)

除了一些问题外,您的代码大多是正确的:

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

你正在使用modulo-11,所以acc可以等于10. ISBN规定在这种情况下“X”应该用作最后一个“数字”,可以写成:

ISBNNo = ISBNNo + (str(acc) if acc < 10 else 'X')

以下是固定代码,示例为number from Wikipediahttp://ideone.com/DaWl6y


回应评论

>>> 255 // 11               # Floor division (rounded down)
23
>>> 255 - (255//11)*11      # Remainder (manually)
2
>>> 255 % 11                # Remainder (operator %)
2

(注意:我正在使用//代表分区。在Python 2中,你也可以简单地使用/,因为你要分割整数。在Python 3中,{ {1}}始终是真正的分割,/是分割。)