Python Struct
From Sigmon
Contents |
shortening URLs
solution #1
>>> import struct, base64
>>> p = struct.pack("I", 1234567890)
>>> p
'\xd2\x02\x96I'
>>> base64.b64encode(p)
'0gKWSQ=='
>>> (v,) = struct.unpack("I", base64.b64decode('0gKWSQ=='))
>>> v
1234567890
solution #2
from http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener
alphabet = map(chr, range(97,123)+range(65,91)) + map(str,range(0,10))
def lookup(k, a=alphabet):
if type(k) == int:
return a[k]
elif type(k) == str:
return a.index(k)
def encode(i, a=alphabet):
'''Takes an integer and returns it in the given base with mappings for upper/lower case letters and numbers 0-9.'''
try:
i = int(i)
except Exception:
raise TypeError("Input must be an integer.")
def incode(i=i, p=1, a=a):
# Here to protect p.
if i <= 61:
return lookup(i)
else:
pval = pow(62,p)
nval = i/pval
remainder = i % pval
if nval <= 61:
return lookup(nval) + incode(i % pval)
else:
return incode(i, p+1)
return incode()
def decode(s, a=alphabet):
'''Takes a base 62 string in our alphabet and returns it in base10.'''
try:
s = str(s)
except Exception:
raise TypeError("Input must be a string.")
return sum([lookup(i) * pow(62,p) for p,i in enumerate(list(reversed(s)))])
This failed.
solution #3
from http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener
import math
class RADIX(object):
codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
base = 62 # len(codeset)
def __init(self, codeset=None):
if codeset != None:
self.codeset = codeset
self.base = len(codeset)
def encode(self, id):
hash = ""
while (id > 0):
hash = self.codeset[int(id % self.base)] + hash
id = math.floor(id / self.base)
return hash
def decode(self, encoded):
id = 0
for index, char in enumerate(encoded[::-1]):
n = self.codeset.find(char)
if n == -1:
return 0 # Invalid hash
id += n * math.pow(self.base, index)
return int(id)
>>> uh = RADIX() >>> uh.encode(1234567890) '1ly7vk' >>> uh.decode(_) 1234567890