there is a lot of information about how to write 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
JavaScript
x
26
26
1
test = "5573497266530355"
2
kazde_druhe = []
3
ostatni = []
4
5
for i in test:
6
if int(i) % 2 == 0:
7
double_digit = int(i) * 2
8
9
if double_digit > 9:
10
p = double_digit - 9
11
kazde_druhe.append(p)
12
else:
13
kazde_druhe.append(double_digit)
14
else:
15
ostatni.append(int(i))
16
17
o = sum(ostatni)
18
k = sum(kazde_druhe)
19
20
total = o+k
21
22
if total % 10 == 0:
23
print(f"Your card is valid ")
24
else:
25
print(f"Your card is invalid ")
26
Finally! Thank you all for your help. Now it is working :-)
JavaScript
1
24
24
1
test = "5573497266530355" kazde_druhe = [] ostatni = []
2
3
for index, digit in enumerate(test):
4
if index % 2 == 0:
5
double_digit = int(digit) * 2
6
print(double_digit)
7
8
if double_digit > 9:
9
double_digit = double_digit - 9
10
kazde_druhe.append(double_digit)
11
else:
12
kazde_druhe.append(double_digit)
13
else:
14
ostatni.append(int(digit))
15
16
o = sum(ostatni)
17
18
k = sum(kazde_druhe)
19
20
total = o+k if total % 10 == 0:
21
print(f"Your card is valid ")
22
else:
23
print(f"Your card is invalid ")
24
Advertisement
Answer
This code works. :)
I fixed you code as much as i could.
JavaScript
1
19
19
1
test = "5573497266530355"
2
#test = "3379513561108795"
3
4
nums = []
5
6
for i in range(len(test)):
7
if (i % 2) == 0:
8
num = int(test[i]) * 2
9
10
if num > 9:
11
num -= 9
12
13
nums.append(num)
14
else:
15
nums.append(int(test[i]))
16
17
print(nums)
18
print((sum(nums) % 10) == 0)
19
I found where your code went wrong.
On the line:
JavaScript
1
3
1
for i in test:
2
if int(i) % 2 == 0:
3
It should be:
JavaScript
1
3
1
for i in range(len(test)):
2
if i % 2 == 0:
3
You should not be using the element of the string you should be using the index of the element.