I am using this code below to generate a number between 1 to 10 continuously until it generates either 9 or 10 before it stops
import random
while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
break
https://stackoverflow.com/a/47477745/9003921
I want to display another item if it generates a number from 1 to 8 for example if it generates the number 3 I want it to print out a name in order from a stack data structure. If it generates the numbers 9 or 10 it would break.
An example of the stack data structure
- Mary
- Peter
- Bob
- John
- Kim
The stack code I'm using is
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)
However, I'm not sure how to proceed from here
I think this is what you want. It generates a random number from 1-10 and prints the number. It does this infinitely unless the number is greater than 8 (9 or 10) - (as in the question). The method
printItem
is called when the number is equal to 3 (this can be changed). This method has one non-self parameter calledrun
(can be renamed). This is what changes which name is printed. It prints the names in the order of the stack - last item is printed first - you could always change this if it is not the order that you want.run
is used as an index for theStack
, which one is subtracted from each time the method is called. Here is the code, you can try it out:I hope this helped!
Just FYI, if you wanted
run
to be a variable specific to the object, you would just add it to Stack's__init__
method.