I am stuck trying to solve a problem on sololearn app.
Problem description -
You need to verify if the given credit card number is valid. For that you need to use the Luhn test.
Here is the Luhn formula:
- Reverse the number.
- Multiple every second digit by 2.
- Subtract 9 from all numbers higher than 9.
- Add all the digits together.
- Modulo 10 of that sum should be equal to 0.
Task:
Given a credit card number, validate that it is valid using the Luhn test. Also, all valid cards must have exactly 16 digits.
Input Format:
A string containing the credit card number you need to verify.
Output Format:
A string: ‘valid’ in case the input is a valid credit card number (passes the Luhn test and is 16 digits long), or ‘not valid’, if it’s not.
Sample Input:
4091131560563988
Sample Output:
valid
My solution -
cc_number = input()
cc_number = list(map(int,cc_number))
cc_number.reverse()
for i in range(1,16,2):
cc_number[i]*=2
for i in range(16):
if cc_number[i]>9:
cc_number[i] -=9
sum_cc = sum(cc_number)
if sum_cc % 10 == 0 and len(cc_number)==16:
print("valid")
else:
print ("not valid")
This code gives correct output in some cases but fails 2 out of 7 test cases. Can you help me find the error in my code?? Thanks in advance!!