python - Luhn 的算法伪代码代码

标签 python

大家好,我是编程界的新手。对于学校练习题,我得到了以下文本,我想将其转换为代码。我已经花了几个小时在上面,但似乎仍然无法弄清楚,但我决心学习这个。我目前遇到错误

  line 7, in <module> if i % 2 == 0: TypeError: not all arguments converted during string formatting 

这是什么意思?我还在学习循环,我不确定它的格式是否正确。谢谢你的时间。

# GET user's credit card number
# SET total to 0
# LOOP backwards from the last digit to the first one at a time
    # IF the position of the current digit is even THEN
        # DOUBLE the value of the current digit
        # IF the doubled value is more than 9 THEN
            # SUM the digits of the doubled value
        # ENDIF
       # SUM the calculated value and the total
    # ELSE
        # SUM the current digit and the total
    # ENDIF
# END loop
# IF total % 10 == 0 THEN
    # SHOW Number is valid
# ELSE
    # SHOW number is invalid
# ENDIF


creditCard = input("What is your creditcard?")
total = 0
for i in creditCard[-1]:
    if i % 2 == 0:
        i = i * 2
        if i > 9:
            i += i
    total = total + i

    else:
        total = total + i

if total % 10 == 0:
    print("Valid")

else:
    print("Invalid")

最佳答案

好吧,我可以看到 2 个问题:

1)当你这样做的时候:

for i in creditCard[-1]

您无需对信用卡进行迭代,您只需取最后一位数字即可。 你可能打算做

for i in creditCard[::-1]

这会将数字从最后一个迭代到第一个

2) 伪代码说,如果它的 POSITION 是偶数,则将数字加倍,而不是数字本身是偶数

所以你可以这样做:

digit_count = len(creditCard)
for i in range(digit_count -1, -1, -1):
    digit = creditCard[i]

或者看看enumerate内置函数

编辑:

完整示例:

creditCard = input("What is your creditcard?")
total = 0
digit_count = len(creditCard)
for i in range(0, digit_count, -1):
    digit = creditCard[i]

    if i % 2 == 0:
        digit = digit  * 2
        if digit  > 9:
            digit = digit / 10 + digit % 10 # also noticed you didnt sum the digits of the number  

    total = total + digit



if total % 10 == 0:
    print("Valid")

else:
    print("Invalid")

关于python - Luhn 的算法伪代码代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40077230/

相关文章:

python - 子类化 QGraphicsLayoutItem 以显示像素图

python - Python中zfill方法的解释

python - 来自 Celery worker 的事件 Django 设置文件

python - 在字典中存储和检索图像 - python

python - 在 python 中执行代码后可以重新初始化变量吗

Python:(悲情)多处理与类方法

python - 选择 Dataframe 中任何列等于列表中任何项目的行

python - 是否需要 python-dev 来安装 pip

python - 参数化pytest fixture

python - 属性错误 : VerifiedHTTPSConnection instance has no attribute '_tunnel_host'