Anyone knows why this Python code doesn't work?


  • 0
    M

    The one on top doesn't work, however the one below it does work. I think they are equivalent.

    def getRandom(self):
        count, rslt = 1, None
        cur = self.head
        while cur:
            if random.random() < 1/count:
                rslt = cur
            count, cur = count + 1, cur.next
        return rslt.val
    
    def getRandom(self):
        count, rslt = 1, None
        cur = self.head
        while cur:
            if random.randint(1, count) == 1:
                rslt = cur
            count, cur = count + 1, cur.next
        return rslt.val

  • 0

    1/2, 1/3, etc are all 0.


  • 0
    M

    @ManuelP I thought this was Python 3, but thanks for pointing this out. Never thought about this.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.