Ad

Random Generator Using Stack Data Structure

- 1 answer

class Stack:
     def __init__(self):
         self.container = []  

     def isEmpty(self):
         return self.size() == 0   

     def push(self, item):
         self.container.append(item)  

     def peek(self) :
         if self.size()>0 :
             return self.container[-1]
         else :
             return None

     def pop(self):
         return self.container.pop()

     def size(self):
         return len(self.container)

s = Stack()
s.isEmpty()
s.push("Cat")
s.push("Dog")
s.push("Horse")
s.push("Snake")
s.push("Lion")
s.push("Fish")
s.push("Bear")
s.push("Tiger")

These are my codes using stack. I am having problems trying to come up with a code that can randomly generate only 3 out of the 8 animals as the output using stack data structure only.

Output Example:

Dog
Snake
Tiger
Ad

Answer

Generate the indexes all at once, then pop the elements one by one and output those at index positions:

import random
sample = random.sample(range(s.size()), 3)
for i in range(s.size()):
    if i in sample:
        print(s.pop())
    else:
        s.pop()

EDIT (reply to follow-up question from comments):

To pick one of the three chosen animals, push each of them on a second stack in the first loop. In the second loop, repeat the exactly same process, only with parameters changed (choose 1 out of 3 instead of 3 out of 8):

import random
sample = random.sample(range(s.size()), 3)
s2 = Stack()
for i in range(s.size()):
    if i in sample:
        animal = s.pop()
        s2.push(animal)
        print(animal)
    else:
        s.pop()

index = random.randint(0, s2.size() - 1)
for i in range(s2.size()):
    if i == index:
        animal = s2.pop()
        print(animal)
    else:
        s2.pop()
Ad
source: stackoverflow.com
Ad