How would you translate this from Perl to Python?

后端 未结 8 2073
忘了有多久
忘了有多久 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:27

    I just tested this up to 1000 against the original perl implementation and diff returns the same results for both. The suffix code is tricky -- this is not a base 36 counter. Hasen J's solution - though it produces a unique timestamp - isn't quite the same since it goes from 'Z' to 'BA', when it should instead go to 'AA' to match the perl ++ operator.

    #!/usr/bin/python
    
    class uniqify:
        def __init__(self):
            self.last_timestamp = -1
            self.next_suffix = 'A'
            return
    
        def suffix(self):
            s = self.next_suffix
            letters = [l for l in self.next_suffix]
            if letters[-1] == 'Z':
                letters.reverse()
                nonz = None
                for i in range(len(letters)):
                    if letters[i] != 'Z':
                        nonz = i
                        break
                if nonz is not None:
                    letters[nonz] = chr(ord(letters[nonz]) + 1)
                    for i in range(0, nonz):
                        letters[i] = 'A'
                else:
                    letters = ['A'] * (len(letters) + 1)
                letters.reverse()
            else:
                letters[-1] = chr(ord(letters[-1]) + 1)
    
            self.next_suffix = ''.join(letters)
            return s
    
        def reset(self):
            self.next_suffix = 'A'
            return
    
        def __call__(self, timestamp):
            if timestamp == self.last_timestamp:
                timestamp_str = '%s%s' % (timestamp, self.suffix())
            else:
                self.last_timestamp = timestamp
                self.reset()
                timestamp_str = '%s' % timestamp
    
            return timestamp_str
    
    uniqify = uniqify()
    
    if __name__ == '__main__':
        for n in range(1000):
            print uniqify(1)
        for n in range(1000):
            print uniqify(2)
    

提交回复
热议问题