天天看點

perl轉python_你如何将這個從Perl翻譯成Python?

看看

this answer for a robust method to convert a number to an alphanumeric id

我現在的代碼不會從’Z’轉到’AA’,而是轉到’BA’,但我想這并不重要,它仍然産生一個唯一的id

from string import uppercase as up

import itertools

def to_base(q, alphabet):

if q < 0: raise ValueError( "must supply a positive integer" )

l = len(alphabet)

converted = []

while q != 0:

q, r = divmod(q, l)

converted.insert(0, alphabet[r])

return "".join(converted) or alphabet[0]

class TimestampUniqifier( object ):

def __init__(self):

self.last = ''

self.counter = itertools.count()

def __call__( self, str ):

if str == self.last:

suf = self.counter.next()

return str + to_base( suf, up )

else:

self.last = str

self.counter = itertools.count()

return str

timestamp_uniqify = TimestampUniqifier()

用法:

timestamp_uniqify('1')

'1'

timestamp_uniqify('1')

'1A'

timestamp_uniqify('1')

'1B'

timestamp_uniqify('1')

'1C'

timestamp_uniqify('2')

'2'

timestamp_uniqify('3')

'3'

timestamp_uniqify('3')

'3A'

timestamp_uniqify('3')

'3B'

你可以稱之為maaaany次,它仍然會産生好的結果:

for i in range(100): print timestamp_uniqify('4')

4

4A

4B

4C

4D

4E

4F

4G

4H

4I

4J

4K

4L

4M

4N

4O

4P

4Q

4R

4S

4T

4U

4V

4W

4X

4Y

4Z

4BA

4BB

4BC

4BD

4BE

4BF

4BG

4BH

4BI

4BJ

4BK

4BL

4BM

4BN

4BO

4BP

4BQ

4BR

4BS

4BT

4BU

4BV

4BW

4BX

4BY

4BZ

4CA

4CB

4CC

4CD

4CE

4CF

4CG

4CH

4CI

4CJ

4CK

4CL

4CM

4CN

4CO

4CP

4CQ

4CR

4CS

4CT

4CU

4CV

4CW

4CX

4CY

4CZ

4DA

4DB

4DC

4DD

4DE

4DF

4DG

4DH

4DI

4DJ

4DK

4DL

4DM

4DN

4DO

4DP

4DQ

4DR

4DS

4DT

4DU