简体   繁体   English

我的列表值更改不正确 - python

[英]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.要求:第一个元素必须是 5 第二个元素必须在 1 到 5 之间 最后一个元素必须是从 luhn 算法返回的 lcheck digit。

i have check digit function with luhn algorithm, so far everything is okay.我有 luhn 算法的校验位 function,到目前为止一切正常。 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.但是当我在 generateMasterCard function 中将参数我的卡号给 generateCheckDigit function 时,我的卡号返回为乘以 2,在 luhn 算法期间相隔一个元素。

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: 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]

You can import copy and use generateCheckDigit(copy.copy(card_number)) as您可以import copy并使用generateCheckDigit(copy.copy(card_number))作为
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". 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它会更改您通过的列表”。 Passing a copy allows you to avoid this.传递副本可以避免这种情况。

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

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