Luhn的算法伪代码编码

时间:2016-10-17 01:14:49

标签: 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")

1 个答案:

答案 0 :(得分:1)

好吧,我可以看到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")