I've implemented the well known Luhn Algorithm in Python. It's a simple one, so it's good for beginners.
import random
from math import ceil
def Luhn(digits):
if digits >= 2:
num = random.randrange(10**(digits-2),10**(digits-1))
num_digits = list(str(num))
for i in range(0,digits-1):
num_digits[i] = int(num_digits[i])
if digits % 2 == 0:
range_start = 0
else:
range_start = 1
for i in range(range_start,ceil((digits+range_start-1)/2)):
if digits % 2 == 0:
num_digits[2*i] *= 2
if num_digits[2*i] > 9:
num_digits[2*i] -= 9
else:
num_digits[2*i-1] *= 2
if num_digits[2*i-1] > 9:
num_digits[2*i-1] -= 9
checksum = sum(num_digits)
last_digit = checksum % 10
if last_digit != 0:
checknum = 10 - last_digit
else:
checknum = 0
num = num*10+checknum
return num
else:
return None
It's a function that takes 1 parameter (digits) and returns a valid number with a given number of digits. The code is pretty straightforward, except for this part:
if digits % 2 == 0:
range_start = 0
else:
range_start = 1
for i in range(range_start,ceil((digits+range_start-1)/2)):
if digits % 2 == 0:
num_digits[2*i] *= 2
if num_digits[2*i] > 9:
num_digits[2*i] -= 9
else:
num_digits[2*i-1] *= 2
if num_digits[2*i-1] > 9:
num_digits[2*i-1] -= 9
Basically what it does is the 'multiplication by 2' part of the algorithm. This part was intentional, so don't take this in consideration. I just wanted to challenge myself.
I would like to get some feedback about the code and things that can be changed.