vendredi 23 novembre 2018

return random values from a stack python

I am trying to return 5 values from a stack and displaying it out. May I ask how I can go about doing it?

Attached is my code on how to solve the problem.

import random
Class Stack:
def __init__(self):
    self.stack = []

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

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

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

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

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

def randomFive(self):
    return self[random.randint(0,len(self)-1)]

list=Stack()
list.push("Tom")
list.push("John")
list.push("Peter")
list.push("Harry")
list.push("Jerry")

for i in range(0,list.size()):
    five = list.randomFive()

The error shown is:
return self[random.randint(0,len(self)-1)]
TypeError: object of type 'Stack' has no len()




Aucun commentaire:

Enregistrer un commentaire