import random def AllSame (t): """ Check if string is composed with only one, repeating character. For instance: >>> AllSame("aaaaaaa") True """ if not t: return False l = t[0] c = 1 for x in t[1:]: c += x==l return c==len(t) # English numbers: digits = { "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "0": "zero", "10": "ten", "11": "eleven", "12": "twelve", "13": "thirteen", "14": "fourteen", "15": "fifteen", "16": "sixteen", "17": "seventeen", "18": "eighteen", "19": "nineteen", "20": "twenty", "30": "thirty", "40": "forty", "50": "fifty", "60": "sixty", "70": "seventy", "80": "eighty", "90": "ninety", "100": "one hundred", "200": "two hundred", "300": "three hundred", "400": "four hundred", "500": "five hundred", "600": "six hundred", "700": "seven hundred", "800": "eight hundred", "900": "nine hundred", "00": "", "1000": "one thousand", "2000": "two thousand", "3000": "three thousand", "4000": "four thousand", "5000": "five thousand", "6000": "six thousand", "7000": "seven thousand", "8000": "eight thousand", "9000": "nine thousand", "000": "thousand", "1000000": "million", "000000": "million", "1000000000": "billion", # For declanative languages. Where thousand changes form. # E.g. In Croatian: 1000=Tisucu 21000=Dvadeset i [jedna tisuca] "001": "one thousand", "002": "two thousand", "003": "three thousand", "004": "four thousand", "005": "five thousand", "006": "six thousand", "007": "seven thousand", "008": "eight thousand", "009": "nine thousand"} def NumberToWord (num, digits=digits, lj=" ", kz=0): """ Explodes a number to word(s). digits is a dictionary containing all major number-word mappings. See the example. lj is the word inserted between tens and ones. kz is internal for recursive control, do not use it manually. """ num = num.strip() if kz==1: t = "" for x in num: if x=="0" and len(t)==0: continue t += x num = t if not num: return "" if kz==-1: e = "" for x in num: e += digits[x]+" " return e[:-1] if AllSame(num) and num[0]=="0": return (len(num)*(digits[num[0]]+" "))[:-1] if num.startswith("0"): return NumberToWord(num, digits, lj, -1) if digits.has_key(num): return digits[num] l = len(num) if l==2: return digits[num[0]+"0"]+lj+digits[num[1]] if l==3 or l==4: return NumberToWord(num[0]+((l-1)*"0"), digits, lj, 1)+" "+NumberToWord(num[1:], digits, lj, 1) if l==5: d1 = num[0]; d2 = num[1] if d1=="1": return (NumberToWord(num[:2], digits, lj, 1)+" "+digits["000"]+" "+NumberToWord(num[2:], digits, lj, 1)).strip() return (digits[d1+"0"]+" "+digits["00"+d2]+" "+NumberToWord(num[2:], digits, lj, 1)).strip() if l==6: d1 = num[0]; d2 = num[1]; d3 = num[2] if d2=="1": m = digits[d2+d3]+" "+digits["000"] else: m = digits[d2+"0"]+" "+digits["00"+d3] return (digits[d1+"00"]+" "+m+" "+NumberToWord(num[3:], digits, lj, 1)).strip() return NumberToWord(num, digits, lj, -1) print NumberToWord(str(random.randint(0, 999999)))