pythonluhn

my list value changing incorrectly - python


im trying to generate mastercard card number. requirements : first element must be 5 second element must be between 1 and 5 last element must be lcheck digit returned from luhn algorithm.

i have check digit function with luhn algorithm, so far everything is okay. but when i give parameter my card number to generateCheckDigit function in generateMasterCard function, my card number is returned as multiplied by 2, one element apart during the luhn algorithm.

sorry for my bad english

here is the codes:

def generateCheckDigit(numbers):

    if len(numbers)%2 == 1:
        for i in range(0,len(numbers),2):
            numbers[i] *= 2
    else:
        for i in range(1,len(numbers),2):
            numbers[i] *= 2

    check_digit = (sum(numbers)*9) % 10

    return check_digit


def generateMasterCard():
    
    card_number = [5, rd.randint(1,5)]

    for i in range(13):
        card_number.append(rd.randint(0,9))

    print(f"first number : {card_number}")

    check_digit = generateCheckDigit(card_number)

    card_number.append(check_digit)

    return card_number

output :

first number : [5, 4, 1, 4, 0, 8, 4, 8, 0, 4, 2, 8, 8, 2, 9]
[10, 4, 2, 4, 0, 8, 8, 8, 0, 4, 4, 8, 16, 2, 18, 4]

Solution

  • You can import copy and use generateCheckDigit(copy.copy(card_number)) as
    Alexey Larionov sais in comments "In Python if you pass to a function some complicated value, like class instance, list, dictionary, etc, then your function can freely modify it. In your case, you do operation numbers[i] *= 2 and it changes the list you passed". Passing a copy allows you to avoid this.