How would you translate this from Perl to Python?

后端 未结 8 2066
忘了有多久
忘了有多久 2021-02-08 03:01

I\'ve got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it\'s never seen it before) or otherwise, it appends some letters to make it uni

8条回答
  •  情书的邮戳
    2021-02-08 03:46

    This is my first time answering, and I used globals, but it seemed the simplest way to me.

    from string import uppercase
    
    last_ts = None
    letters = None
    
    def increment(letters):
        if not letters:
            return "A"
        last_letter = letters[-1]
        if last_letter == "Z":
            return increment(letters[:-1])  + "A" 
        return letters[:-1] + uppercase[uppercase.index(last_letter) + 1]
    
    def uniquify(timestamp):
        global last_ts, letters
        if timestamp == last_ts:
            letters = increment(letters)
            return timestamp + letters
        last_ts = timestamp
        letters = None
        return timestamp
    
    print uniquify("1")
    print uniquify('1')
    print uniquify("1")
    print uniquify("2")
    for each in range(100): print uniquify("2")
    
    
    1
    1A
    1B
    2
    2A
    2B
    2C
    2D
    2E
    2F
    2G
    2H
    2I
    2J
    2K
    2L
    2M
    2N
    2O
    2P
    2Q
    2R
    2S
    2T
    2U
    2V
    2W
    2X
    2Y
    2Z
    2AA
    2AB
    2AC
    2AD
    2AE
    2AF
    2AG
    2AH
    2AI
    2AJ
    2AK
    2AL
    2AM
    2AN
    2AO
    2AP
    2AQ
    2AR
    2AS
    2AT
    2AU
    2AV
    2AW
    2AX
    2AY
    2AZ
    2BA
    2BB
    2BC
    2BD
    2BE
    2BF
    2BG
    2BH
    2BI
    2BJ
    2BK
    2BL
    2BM
    2BN
    2BO
    2BP
    2BQ
    2BR
    2BS
    2BT
    2BU
    2BV
    2BW
    2BX
    2BY
    2BZ
    2CA
    2CB
    2CC
    2CD
    2CE
    2CF
    2CG
    2CH
    2CI
    2CJ
    2CK
    2CL
    2CM
    2CN
    2CO
    2CP
    2CQ
    2CR
    2CS
    2CT
    2CU
    2CV
    

提交回复
热议问题