from time import time import random from sets import Set def factorial(n): assert n >=1 if n == 1: return 1 else: return n * factorial(n-1) class SmurlFolder: def __init__(self, minlength_alpha=1, minlength_numeric=1, upper_and_lower=False): self.minlength_alpha = minlength_alpha self.minlength_numeric = minlength_numeric self.upper_and_lower = upper_and_lower def _generateID(self): """ generate a new ID that hasn't been instanciated in this self before """ assert self.minlength_alpha >= 1 assert self.minlength_numeric >= 1 letters = "abcdefghijklmnopqrstuvwxyz" if self.upper_and_lower: letters += letters.upper() numbers = "0123456789" while 1: try: genid_bits = random.sample(letters, self.minlength_alpha) + \ random.sample(numbers, self.minlength_numeric) except: letters += letters numbers += numbers continue unique = Set(genid_bits) possible_combinations = factorial(len(unique)) combinations = [] while len(combinations) < possible_combinations: random.shuffle(genid_bits) combination = ''.join(genid_bits) if combination not in combinations: if not hasattr(self, combination): return combination combinations.append(combination) if self.minlength_numeric < self.minlength_alpha: self.minlength_numeric += 1 else: self.minlength_alpha += 1 def createSmurl(self, url): """ create a Smurl object and return the object """ if not url.startswith('http'): url = 'http://'+url genid = self._generateID() inst = Smurl(genid, url) class SmurlFolderDummy(SmurlFolder): def __init__(self): SmurlFolder.__init__(self) def setDummy(self, item): self.__dict__[item] = 1 def __str__(self): return ' '.join(self.__dict__.keys()) def __len__(self): return len(self.__dict__.keys()) def test(): folder = SmurlFolderDummy() folder.setDummy('a1') folder.setDummy('b2') for i in range(20000): x = folder._generateID() folder.setDummy(x) t0=time() for i in range(10): x = folder._generateID() folder.setDummy(x) t1=time() print "10 more took", t1-t0 print len(folder) def profile(): folder = SmurlFolderDummy() t0=time() folder.setDummy('a1') tp=time()-t0 total = 0 RUNS = 20000 for i in range(RUNS): t0=time() x = folder._generateID() t = time()-t0 folder.setDummy(x) # if i%10==0: # print t total += t print "Total:", total print "Average:", total/RUNS print str(folder)[-100:] print folder.minlength_alpha, folder.minlength_numeric profile()