# Generate Constrained Number Sequences in Python

Some applications require generating a number sequences that must fulfill multiple constraints. I solved this problem with a python script and a couple of functions using lists.

I was interested in generating 10-digit numbers that met the following conditions:

- digits 0 and 1 (from left to right) are random from 01 to 25
- digit 2 is < 7
- digits 3 to 8 are random

Digit 9 is a checksum digit. It is calculated by looking at the first 9 digits to the left. Digits on even positions are doubled. If the product is larger than 9, we keep the difference. Digits on odd positions are kept as is or multiplied by one. The sum of the products is subtracted for the nearest tenth. This becomes the checksum digit.

My code has three functions or sections:

1 2 3 4 5 6 7 8 9 10 |
def generate (number) : '''function that takes an integer for how many sequences to generate. It generates digits 0 to 8 of each sequence.''' def checksum () : '''function that calculates the checksum digit on position 9 ''' def verify (string) : '''function that performs a sanity check on each sequence generated according to the same rules it was created.''' |

Some of the more interesting bits of code, are to create a random six-digit number sequence

1 2 3 |
digits3to9 = "%06d" % random.randint(1,999999) # random 6-digit number w/ fixed width digits[3:9] = [int(x) for x in digits3to9] # add six digit number to digit list digitStr = ''.join(str(e) for e in digits) # join digit list into a string |

The checksum function is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def checksum(digitStr): '''function that calculates the checksum digit on position 9 ''' sum = 0 digit10 = 0 for i in range(len(digitStr)): if (i % 2 == 0): # digits in even positions if (2 * digitStr[i] > 9): # get doubled. If product > 9, subtract 9 sum += (2 * int(digitStr[i])) - 9 else: sum += 2 * int(digitStr[i]) elif (i == 9): # for tenth digit in position 9 if sum % 10 == 0 or sum == 0: # if the accumulated sum is a multiple of digit10 = 0 # ten or zero, tenth digit = 0 else: # else: digit = difference to closest tenth. digit10 = 10 - (sum % 10) else: sum += digitStr[i] # continue accumulating sum for other digits return digit10 # return checksum digit |

Enjoy!