Python 数组中总是剩余一个多余的元素

Python 数组中总是剩余一个多余的元素,python,arrays,element,Python,Arrays,Element,我在做信用卡验证器。那个球体对我来说是新的,所以请不要笑:D 我想在没有图书馆的情况下完成它 def creditCardValidation(creditcard): creditcard = creditcard.replace( ' ', '' ) creditcard = [int(i) for i in creditcard] evens = creditcard[::2] odds = creditcard[1::2] evens = [ele

我在做信用卡验证器。那个球体对我来说是新的,所以请不要笑:D 我想在没有图书馆的情况下完成它

def creditCardValidation(creditcard):
    creditcard = creditcard.replace( ' ', '' )
    creditcard = [int(i) for i in creditcard]
    evens = creditcard[::2]
    odds = creditcard[1::2]
    evens = [element * 2 for element in evens]

    for j in evens:
        if j >= 10:
            j = [int(d) for d in str(j)]
            for x in j:
                evens.append(x)

    for j in evens:
       if j >= 10:        
            evens.remove(j)
    return ((sum(evens) + sum(odds)) % 10 == 0)
creditCardValidation('1234 5678 9101 1213')

creditCardValidation('45612612345464')

creditCardValidation('45612612345467')

因此,问题出在数组evens中。 它回来了

[2,6,14,0,2,2,1,0,1,4,1,8]

[8,4,2,2,6,12,1,2,1,0,1,2]

[8,4,2,2,6,12,1,2,1,0,1,2]


它应该返回相同的结果,但大于10的结果除外。一切正常。看看第一个数组,18个被删除,10个被删除,但14个没有被删除。

在迭代数组时删除并不是最好的做法,并且在迭代时会导致跳过数组中的一些元素,因此这是一种更安全的方法

    for j in evens:
       if j >= 10:        
            evens.remove(j)
是收集要在另一个列表中删除的所有元素,如果使用
numpy arrrays
或逐个删除它们,则从原始列表中减去这些元素,因为python列表没有定义从一个数组减去另一个数组的减法运算

to_remove = []
for j in evens:
  if j >= 10:        
    to_remove.append(j)
for j in to_remove:
  events.remove(j)
或者你可以将其列入白名单而不是黑名单

small_evens = []
for j in evens:
  if j < 10:        
    small_evens.append(j)
# use small_evens and discard evens array
small_evens=[]
对于晚上的j:
如果j<10:
小偶数追加(j)
#使用小的偶数并丢弃偶数数组
有几个问题:

  • Python没有索引数组,因此
    evens[::2]
    实际上返回第一位、第三位等数字。Luhn的算法要求偶数位数(假设1个索引)加倍
  • 您不应该修改正在迭代的列表
您可以简化,删除许多列表创建:

def creditCardValidation(creditcard):
    *creditcard, checkdigit = creditcard.replace(' ', '')

    total = 0
    for i, digit in enumerate(map(int, creditcard), 1):
        if i % 2 == 0:
            digit *= 2
            total += digit // 10   # Will be zero for single digits
        total += digit % 10

    return 9*total % 10 == int(checkdigit)

In []:
creditCardValidation('1234 5678 9101 1213')

Out[]:
True

In []:
creditCardValidation('4561 2612 1234 5464')

Out[]:
False

非常感谢您,但此模型无论如何都不会返回正确答案。如果您使用的是Luhn算法,则通常将
total
乘以
9
,并使用最后一位数字作为校验位。更新!