【发布时间】:2021-06-07 00:04:29
【问题描述】:
我正在编写一个程序来使用 Luhn 算法检查卡号是否可能有效。
num = "79927398713" #example num
digits = [int(x) for x in num]
reverse = digits[1:][::2][::-1] #step 1: start from rightmost digit, skip first, skip every other
count = 0
digitsum = 0
print(reverse) #output here is: [1, 8, 3, 2, 9]
for x in (reverse):
reverse[count] *= 2
if reverse[count] > 9:
for x in str(reverse[count]): #multiply each digit in step 1 by 2, if > 9, add digits to make single-digit number
digitsum += int(x)
reverse[count] = digitsum
count += 1
digitsum = 0
count = 0
print(reverse) #output here is [2, 7, 6, 4, 9]
基本上,我想将 [2, 7, 6, 4, 9] 输入回列表digits 中的相应位置。它看起来像这样(星号中的数字已更改)
[7, **9**, 9, **4**, 7, **6**, 9, **7**, 7, **2**, 3]
问题是,我必须向后阅读digits,跳过第一个(技术上是最后一个)元素,然后从那里跳过所有其他元素,每次都替换值。
我是不是走错了路/让自己太难了?或者有没有办法向后索引,跳过第一个(技术上是最后一个)元素,然后跳过所有其他元素?
【问题讨论】:
标签: python loops iteration reverse luhn