基于26个字母的tiny_uri , 类似sina t.cn 功能
#coding=utf-8
import os, sys
import string
import random
import re
Dict = string.ascii_lowercase
MAXLEN = len(Dict)
def tiny_uri(uri="t.cn/zzzz", domain="t.cn"):
"""tiny uri base on ascii_lowercase carry"""
macth = re.match(r"%s/(.+)" % domain, uri)
macths = macth.groups(0)
if macths:
uri = macths[0]
else:
return None
loop_index = 0
carry = 0
stack = []
for i in reversed(uri):
stack.append(i)
for u in stack:
index = Dict.find(u)
if index < 0:
continue
if index >= (MAXLEN - 1):
#carry bit
stack[loop_index] = Dict[0]
carry = 1
else:
#add on bit
stack[loop_index] = Dict[index + 1]
carry = 0
break
loop_index += 1
if carry > 0:
stack.append(Dict[0])
return "".join(stack)[::-1]
if __name__ == "__main__":
#test
for i in xrange(100):
uri = Dict[random.randint(0, MAXLEN - 1)]
print " * " * 20
print "before uri:", uri
result = tiny_uri("t.cn/%s" % uri)
print "after uri:", result
assert uri != result
print
print "result:", tiny_uri("t.cn/ccaad")
* * * * * * * * * * * * * * * * * * * *
befor uri: r
after uri: s
result: ccaae