Implementation of Luhn Formula

后端 未结 8 2121
礼貌的吻别
礼貌的吻别 2020-12-19 15:38

I was trying to implement the Luhn Formula in Python. Here is my code:

import sys


def luhn_check(number):
    if number.isdigit():
        last_digit = int(         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-19 16:28

    The following might help some people to start with the Luhn algorithm in python.

    num = list(input("Please enter the number to test (no space, no symbols, only \
    numbers): "))
    
    num = list(map(int, num))[::-1] #let's transform string into int and reverse it
    
    for index in range(1,len(num),2):
        if num[index]<5:
            num[index] = num[index] *2
        else: #doubling number>=5 will give a 2 digit number
            num[index] = ((num[index]*2)//10) + ((num[index]*2)%10)
    
    checksum=sum(num)
    
    print("checksum= {}".format(checksum))
    
    if checksum%10 !=0:
        print('the number is not valid')
    else:
        print('the number is valid!')
    

提交回复
热议问题