为什么我的代码输出0000000000000作为一个无效的ISBN号?

2024-09-22 14:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

0000000000000是一个有效的ISBN号码,但我的代码说它是无效的。 我的代码采用13位数字,并检查它是否有效。你知道吗

ISBN的前12位数字中的每一位交替乘以1和3。然后,我们把它们加起来,除以10,得到提醒。如果10减去提醒等于第13位,那么它是有效的。你知道吗

isbnNunmberCheck=input()

n1=int(isbnNunmberCheck[0])*1
n2=int(isbnNunmberCheck[1])*3
n3=int(isbnNunmberCheck[2])*1
n4=int(isbnNunmberCheck[3])*3
n5=int(isbnNunmberCheck[4])*1
n6=int(isbnNunmberCheck[5])*3
n7=int(isbnNunmberCheck[6])*1
n8=int(isbnNunmberCheck[7])*3
n9=int(isbnNunmberCheck[8])*1
n10=int(isbnNunmberCheck[9])*3
n11=int(isbnNunmberCheck[10])*1
n12=int(isbnNunmberCheck[11])*3

k=10-(n1+n2+n3+n4+n5+n6+n7+n8+n9+n10+n11+n12)%10

if k==int(isbnNunmberCheck[-1]):
    print("Valid")
else:
    print("Invalid")

Tags: 代码数字intisbnn2n6n3n1
3条回答

If 10 minus the remainder is equal to the 13th digit, then it's valid.

对于ISBN,“10减去余数”是10 - 0 % 10 = 10。这不等于第13位,即0。因为10 != 0,ISBN是无效的。你知道吗

但你的代码太冗长了。让我们考虑一种更好的编写算法的方法:

isbn_str = input()

k = 10 - (sum(map(int, isbn_str[0:-1:2])) + sum(map(int, isbn_str[1:-1:2]))*3) % 10

print(k)

if k == int(isbn_str[-1]):
    print("Valid")
else:
    print("Invalid")

请注意,可以使用与对列表进行切片相同的方式对字符串进行切片,即使用语法start:stop:stepmap+int延迟地将iterable的每个元素转换为整数,sum获取这些整数并对其求和。另见Understanding Python's slice notation。你知道吗

好吧,你的和是0,所以余数是0,那么(10-余数)=10,那么10!= 0. 你知道吗

我觉得你的想法一开始就不正确。你知道吗

关键是:

If this calculation results in an apparent check digit of 10, the check digit is 0

从你的评论,而不是你原来的问题。你知道吗

因此,如果校验位是10,那么在比较中实际上需要使用0。你知道吗

计算您的支票号码,然后:

k = 0 if k == 10 else k

相关问题 更多 >