How would you translate this from Perl to Python?

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

    The class is generic and boring, but This is my very first recursive generator. <3

    def stamptag():
        yield ''
        prefixtag = stamptag()
        prefix = prefixtag.next()
        while True:
            for i in range(ord('A'),ord('Z')+1):
                yield prefix+chr(i)
            prefix = prefixtag.next()
    
    tagger = stamptag()
    for i in range(3000):
        tagger.next()
    print tagger.next()
    
    class uniquestamp:
        def __init__(self):
            self.timestamp = -1
            self.tagger = stamptag()
    
        def format(self,newstamp):
            if self.timestamp < newstamp:
                self.tagger = stamptag()
                self.timestamp = newstamp
            return str(newstamp)+self.tagger.next()
    
    stamper = uniquestamp()
    print map(stamper.format, [1,1,1,2,2,3,4,4])
    

    output:

    DKJ
    ['1', '1A', '1B', '2', '2A', '3', '4', '4A']
    
    0 讨论(0)
  • 2021-02-08 03:47

    Quite similar to Ali A, but I'll post mine anyway:

    class unique_timestamp:
        suffixes = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        def __init__(self):
            self.previous_timestamps = {}
            pass
        def uniquify(self, timestamp):
            times_seen_before = self.previous_timestamps.get(timestamp, 0)
            self.previous_timestamps[timestamp] = times_seen_before + 1
            if times_seen_before > 0:
                return str(timestamp) + self.suffixes[times_seen_before]
            else:
                return str(timestamp)
    

    Usage:

    >>> u = unique_timestamp()
    >>> u.uniquify(1)
    '1'
    >>> u.uniquify(1)
    '1A'
    >>> u.uniquify(1)
    '1B'
    >>> u.uniquify(2)
    '2'
    
    0 讨论(0)
提交回复
热议问题