Hot Potato
  • Children line up in a circle and pass an item from neighbor to neighbor as fast as they can
  • To simulate the circle, use a queue and assume that the child holding the potato will be at the front of the queue
  • Upon passing the potato, the simulation will simply dequeue and then immediately enqueue that child, putting her at the end of the line
  • After num dequeue/enqueue operations, the child at the front will be removed permanently and another cycle will begin
  • This process will continue until only one name remains
  • # QueueModule.py
    #!/usr/bin/python3
    class Queue(object):
        def __init__(self):
            self.items = []
    
        def isEmpty(self):
            return len(self.items) == 0
    
        def enqueue(self, v):
            try:
                self.items.insert(0,v)
                return True
            except Exception as e:
                return False
    
        def dequeue(self):
            try:
                item = self.items.pop()
                return item
            except Exception as e:
                return None
    
        def size(self):
            return len(self.items)
    
        def front(self):
            if self.size() == 0:
                return None
            return self.items[self.size()-1]
    
        def rear(self):
            if self.size() == 0:
                return None
            return self.items[0]
    
        def __str__(self):
            s = 'rear ->'
    
            output = []
    
            for item in self.items:
                output.append(str(item))
    
            s += '->'.join(output)
    
            s += '-> front'
    
            return s
                
    #!/usr/bin/python3
    from QueueModule import Queue
    
    def potato(q, num):
    
        for i in range(num):
            item = q.dequeue()
            q.enqueue(item)
    
        q.dequeue()
    
    def main():
        q = Queue()
    
        q.enqueue('Bill')
        q.enqueue('David')
        q.enqueue('Susan')
        q.enqueue('Jane')
        q.enqueue('Kent')
        q.enqueue('Brad')
    
        print(q)
    
        while q.size() > 1:
            potato(q, 4)
            print(q)
    
    if __name__ == '__main__':
        main()
                
    Reference
  • Problem Solving with Algorithms and Data Structures using Python