I am making a program to check whether a card number is potentially valid using the Luhn algorithm.
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]
basically, I want to input [2, 7, 6, 4, 9] back into the corresponding places in the list digits
. It would look like this (changed numbers in asterisks)
[7, **9**, 9, **4**, 7, **6**, 9, **7**, 7, **2**, 3]
the problem is, I would have to read digits
backwards, skipping the first (technically last) element, and skipping every other element from there, replacing the values each time.
Am I going about this the wrong way/making it too hard on myself? Or is there a way to index backwards, skipping the first (technically last) element, and skipping every other element?
You can do this with simple indexing
Once you have the variable reverse
, you can index on the left hand side:
# reversed is [2, 7, 6, 4, 9] here
digits[1::2] = reversed(reverse) # will place 9,4,6,7,2 in your example
Note, you can use this trick too for your line where you initialize reverse
reverse = digits[1::2][::-1]
I think you could even use:
reverse = digits[-1 - len(digits) % 2::-2]
which should be even more efficient
Running timeit
, the last solution of digits[-1 - len(digits) % 2::-2]
on an array of size 10,000 was 3.6 times faster than the original, I'd highly suggest using this