这个问题来自codewar。
ISBN-10 identifiers are ten digits long. The first nine characters are digits 0-9. The last
digit can be 0-9 or X, to indicate a value of 10.
An ISBN-10 number is valid if the sum of the digits multiplied by their position modulo 11
equals zero.
我的代码
def valid_ISBN10(isbn):
sum = 0
if len(isbn) == 10 and isbn[0:8].isdigit():
for i,x in enumerate(isbn):
if x != 'X':
sum += (int(x))*(i+1)
if isbn[9] == 'X':
sum += 100
return sum % 11 == 0
else:return False
当我尝试它的显示105通过,4 failed.when再次尝试显示103通过,6失败。我不明白why.But,我想我没有在我的code.Can中提到所有的规则,你能告诉我我在哪里做了mistake.should,我替换了其中的任何东西吗?
发布于 2021-07-30 09:03:44
你的函数实际上是错误的。下面是一个有效的ISBN10代码:048665088X
。您的函数返回它为False
。
下面的函数返回True
,并确保您不必删除许多ISBN10代码中存在的破折号
def valid_ISBN10(isbn):
remove_dashes = isbn.replace('-', '')
if (len(remove_dashes) != 10):
return False
result = 0
for index, multiplier in enumerate(reversed(range(1, 11))):
char = remove_dashes[index]
if char.isalpha() and char == 'X' and not index == 9:
return False
elif char.isalpha() and not char == 'X':
return False
elif char.isalpha() and char == 'X' and index == 9:
result = result + (10 * multiplier)
else:
result = result + (int(char) * multiplier)
if not (result % 11):
return True
return False
https://stackoverflow.com/questions/68587793
复制相似问题