-1

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()
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
Wei Long
  • 1
  • 1
  • 1
  • try to not overwrite names of built-in objects like `list` – Azat Ibrakov Nov 24 '18 at 06:04
  • also `self[random.randint(0,len(self)-1)]` probably should be `self[random.randint(0,len(self.stack)-1)]` or you should define `__len__` method – Azat Ibrakov Nov 24 '18 at 06:05
  • I have tried both methods but there is still an error which says `return(self[random.randint(0,len(self.stack)-1)]) AttributeError: 'Stack' object has no attribute 'stack` – Wei Long Nov 25 '18 at 03:20

1 Answers1

1

Error is caused by statement in randomFive method

self[random.randint(0,len(self)-1)]

because self is an instance of Stack which has no __len__ method available and for user-defined classes len built-in function tries to call it and raises an error if there is no any (more info at this thread).

Fast fix would be to change it to

self[random.randint(0,len(self.stack)-1)]

but in longer perspective it will be better to define your own __len__ method like

class Stack:
    ...
    def __len__(self):
        return len(self.stack)

after that your original randomFive method should work.

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50