Ad
Random Generator Using Stack Data Structure
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad