Created
April 28, 2010 10:24
-
-
Save chl/381970 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# chl, 2010-04-27 | |
# http://blog.tech.stylefeeder.com/2008/05/27/generating-primary-keys/ | |
import math | |
NUM = "0123456789" | |
LOWER = "abcdefghijklmnopqrstuvwxyz" | |
UPPER = LOWER.upper() | |
ALPHANUM = NUM + LOWER + UPPER | |
ASCII_94 = [chr(33 + x) for x in xrange(94)] | |
def is_prime(n): | |
if n < 2: | |
return False | |
for x in xrange(2, int(math.sqrt(n)) + 1): | |
if n % x == 0: | |
return False | |
return True | |
def next_prime(x): | |
while not is_prime(x): | |
x += 1 | |
return x | |
def _base(x, b): | |
while x: | |
yield x % b | |
x //= b | |
def base(x, b): | |
return list(reversed(list(_base(x, b)))) | |
def _keyseq(n, k, c=0): | |
while True: | |
yield c | |
c = (c + k) % n | |
def keyseq(alphabet=ALPHANUM, length=5, start=0): | |
a = len(alphabet) | |
n = a ** length | |
# determine k co-prime to n | |
p, k = next_prime(a + 1), 1 | |
while k < n: | |
p = next_prime(p + 1) | |
k = p * k | |
return ("".join(alphabet[d] for d in base(x, a)).rjust(length, alphabet[0]) for x in _keyseq(n, k, int(start % n))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment