How would you translate this from Perl to Python?

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

    Looking at the problem it seems like a good fit for a coroutine (Python 2.5 or higher). Here's some code that will roughly produce the same result:

    def uniqify():
        seen = {}
        val = (yield None)
        while True:
            if val in seen:
                idxa, idxb = seen[val]
                idxb += 1
            else:
                idxa, idxb = (len(seen)+1, ord('a'))
            seen[val] = (idxa, idxb)
            uniq = "%s%s" % (idxa, chr(idxb))
            val = (yield uniq)
    

    And here's how you use it:

    >>> u = send.uniqify()
    >>> u.next() #need this to start the generator
    >>> u.send(1)
    '1a'
    >>> u.send(1)
    '1b'
    >>> u.send(1)
    '1c'
    >>> u.send(2)
    '2a'
    >>> u.send(2)
    '2b'
    >>> u.send(1) #you can go back to previous values
    '1d'
    >>> u.send('stringy') #you can send it anything that can be used as a dict key
    '3a'
    

提交回复
热议问题