简体   繁体   English

如何解决Luhn算法

[英]How to solve Luhn algoritm

there is a lot of information about how to write Luhn algortim.有很多关于如何编写 Luhn algortim 的信息。 I'm trying it too and I think that I'am very close to succes but I have some mistake in my code and dont know where.我也在尝试,我认为我非常接近成功,但我的代码中有一些错误,不知道在哪里。 The test card is VALID card but my algorithm says otherwise.测试卡是有效卡,但我的算法另有说明。 Don't you know why?你不知道为什么吗? Thx for help感谢帮助

test = "5573497266530355"
kazde_druhe = []
ostatni = []

for i in test:
    if int(i) % 2 == 0:
        double_digit = int(i) * 2

        if double_digit > 9:
            p = double_digit - 9
            kazde_druhe.append(p)
        else:
            kazde_druhe.append(double_digit)
    else:
        ostatni.append(int(i))

o = sum(ostatni)
k = sum(kazde_druhe)

total = o+k

if total % 10 == 0:
    print(f"Your card is valid ")
else:
    print(f"Your card is invalid ")

Finally.最后。 Thank you all for your help: Now it is working :-)谢谢大家的帮助:现在它正在工作:-)

        test = "5573497266530355" kazde_druhe = [] ostatni = []
        
        for index, digit in enumerate(test):
            if index % 2 == 0:
                double_digit = int(digit) * 2
                print(double_digit)
        
                if double_digit > 9:
                    double_digit = double_digit - 9
                    kazde_druhe.append(double_digit)
                else:
                    kazde_druhe.append(double_digit)
            else:
                ostatni.append(int(digit))
    
     o = sum(ostatni)
    
     k = sum(kazde_druhe) 
    
    total = o+k if total % 10 == 0:
            print(f"Your card is valid ")
 else:
            print(f"Your card is invalid ")

From this description从这个描述

2. With the payload, start from the rightmost digit. 2. 对于有效载荷,从最右边的数字开始。 Moving left, double the value of every second digit (including the rightmost digit).向左移动,每隔一个数字(包括最右边的数字)的值加倍。

You have to check the digit position, not the number itself.您必须检查数字 position,而不是数字本身。

Change to this:更改为:

for i in range(len(test)):
    if i % 2 == 0:

This code works.此代码有效。 :) :)

I fixed you code as much as i could.我尽可能多地修复了你的代码。

test = "5573497266530355"
#test = "3379513561108795"

nums = []

for i in range(len(test)):
    if (i % 2) == 0:
        num = int(test[i]) * 2
        
        if num > 9:
            num -= 9

        nums.append(num)
    else:
        nums.append(int(test[i]))

print(nums)
print((sum(nums) % 10) == 0)

I found where your code went wrong.我发现你的代码哪里出错了。

On the line:在线上:

for i in test:
    if int(i) % 2 == 0:

It should be:它应该是:

for i in range(len(test)):
    if i % 2 == 0:

You should not be using the element of the string you should be using the index of the element.你不应该使用你应该使用元素索引的字符串元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM