首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在python中制作ISBN-10标识符

在python中制作ISBN-10标识符
EN

Stack Overflow用户
提问于 2021-07-30 08:28:28
回答 1查看 157关注 0票数 1

这个问题来自codewar。

代码语言:javascript
运行
复制
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.

我的代码

代码语言:javascript
运行
复制
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,我替换了其中的任何东西吗?

EN

回答 1

Stack Overflow用户

发布于 2021-07-30 09:03:44

你的函数实际上是错误的。下面是一个有效的ISBN10代码:048665088X。您的函数返回它为False

下面的函数返回True,并确保您不必删除许多ISBN10代码中存在的破折号

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68587793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档