Skip to content

Instantly share code, notes, and snippets.

@pylemon
Last active August 29, 2015 13:57
Show Gist options
  • Save pylemon/9381567 to your computer and use it in GitHub Desktop.
Save pylemon/9381567 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from random import SystemRandom
import sys
import re
system_random = SystemRandom()
def base36_to_int(s):
if len(s) > 13:
raise ValueError("Base36 input too large")
value = int(s, 36)
if value > sys.maxint:
raise ValueError("Base36 input too large")
return value
def int_to_base36(i):
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
factor = 0
if not 0 <= i <= sys.maxint:
raise ValueError("Base36 conversion input too large or incorrect type.")
# Find starting factor
while True:
factor += 1
if i < 36 ** factor:
factor -= 1
break
base36 = []
# Construct base36 representation
while factor >= 0:
j = 36 ** factor
base36.append(digits[i // j])
i = i % j
factor -= 1
return ''.join(base36)
def generateCode(count=100):
"""Base 36 is the most compact case-insensitive alphanumeric numeral system using ASCII characters"""
low = base36_to_int('100000000000')
high = base36_to_int('zzzzzzzzzzzz')
cnt = 0
for i in xrange(count*10):
if cnt > count:
break
slug = int_to_base36(system_random.randint(low, high))
fuzzy_letter = re.compile(r'.*?[o0i1]+?.*', re.IGNORECASE)
if not fuzzy_letter.match(slug):
cnt += 1
code = []
for i in xrange(0, len(slug), 4):
code.append(slug[i:i + 4])
yield u'-'.join(code).upper()
if __name__ == "__main__":
codes = generateCode(int(sys.argv[1]))
for c in codes: print c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment