Hello I am trying to make a function in python to generate valid IMEI numbers so here is my function.The IMEI validation uses the Luhn algorithm so I am trying to implement it in my script.
def getImei():
num = ''
suma = 0
for i in range(0,13):
digit = random.randrange(0,9)
suma = suma + digit
num = num + str(digit)
suma = suma * 9
digit = suma % 10
num = num + str(digit)
return num
The function however fails to generate valid IMEI numbers. I found an article on wikipedia that tells me how to generate the check digit ( http://en.wikipedia.org/wiki/Luhn_algorithm )
The check digit (x) is obtained by computing the sum of digits then computing 9 times that value modulo 10 (in equation form, (67 * 9 mod 10)). In algorithm form: 1.Compute the sum of the digits (67). 2.Multiply by 9 (603). 3.The last digit, 3, is the check digit.
Am I missing something or the wiki is wrong ?
Note that numbers at odd (from the end, starting from 0) postions are doubled, so you have to add it to your code, for example following code will return luhn checksum:
Here
(1 + i%2)
multiplier equals2
for odd positioned numbers, and1
for even positioned. Thensum(divmod(..., 10))
returns sum of digits for a (possibly) two digit number, and outer sum sums resulting sequence.You can use it to generate valid number sequences:
Demo: