Luhns Algorithm

Hey, I'm doing a moon algorithm for a school assignment.

Several outputs are output correctly; however, some of them are not.

0004222222222222It gives me everything 44,

and

0378282246310005It gives me the total amount 48,

for a few examples.

I know that my code is not the cleanest since I'm a beginner, but if someone can determine where I get my error, I would really appreciate it

Here is my code:

cardNumber = input( "What is your card number? ")
digit = len(cardNumber)
value = 0
total = 0
while ( len( cardNumber ) == 16 and digit > 0):
    # HANDLE even digit positions
    if ( digit % 2 == 0 ):
        value = ( int( cardNumber[digit - 1]) * 2 )
        if( value > 9 ):
            double = str( value )
            value = int( double[:1] ) + int( double[-1] )
            total = total + value
            value = 0
            digit = digit - 1
        else:
            total = total + value
            value = 0
            digit = digit - 1
    # HANDLE odd digit positions
    elif ( digit % 2 != 0):
        total = total + int( cardNumber[digit - 1] )
        digit = digit - 1
+4
source share
2 answers

You understand almost everything. Just that the last digit (or the first behind) should be considered odd for your 16-digit card. Therefore, you must install:

digit = len(cardNumber) - 1

>= 0 ( ); , len( cardNumber ) == 16 , :

while digit >= 0:

, , 1:

value = int(cardNumber[digit]) * 2
...
...
total = total + int(cardNumber[digit])
+2

, , , , "" "" . , " " , :

  • ,
  • , ,

: 1234 - EOEO, 12345 - OEOEO (O , E )

Here's the fixed code (I only changed three lines, see comments):

digit = len(cardNumber)
value = 0
total = 0
while  digit > 0: # I removed the length condition
    # HANDLE even digit positions
    if ( (len(cardNumber)+1-digit) % 2 == 0 ): # <- modification here
        value = ( int( cardNumber[digit - 1]) * 2 )
        if( value > 9 ):
            double = str( value )
            value = int( double[:1] ) + int( double[-1] )
            total = total + value
            digit = digit - 1
        else:
            total = total + value
            digit = digit - 1

    # HANDLE odd digit positions
    elif ( (len(cardNumber)+1-digit) % 2 != 0): # <- modification here
        value=int( cardNumber[digit - 1] )
        total = total + int( cardNumber[digit - 1] )
        digit = digit - 1

return total

Some tests:

In : '0378282246310005' ->  Out : 60
In : '00378282246310005' ->  Out : 60
In : '0004222222222222' ->  Out : 40
0
source

Source: https://habr.com/ru/post/1657934/


All Articles