return random values from a stack python












-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()









share|improve this question

























  • try to not overwrite names of built-in objects like list

    – Azat Ibrakov
    Nov 24 '18 at 6: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 6: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 3:20


















-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()









share|improve this question

























  • try to not overwrite names of built-in objects like list

    – Azat Ibrakov
    Nov 24 '18 at 6: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 6: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 3:20
















-1












-1








-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()









share|improve this question
















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()






python python-3.x random stack






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 12:13









Azat Ibrakov

4,10271530




4,10271530










asked Nov 24 '18 at 5:58









Wei LongWei Long

111




111













  • try to not overwrite names of built-in objects like list

    – Azat Ibrakov
    Nov 24 '18 at 6: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 6: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 3:20





















  • try to not overwrite names of built-in objects like list

    – Azat Ibrakov
    Nov 24 '18 at 6: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 6: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 3:20



















try to not overwrite names of built-in objects like list

– Azat Ibrakov
Nov 24 '18 at 6:04





try to not overwrite names of built-in objects like list

– Azat Ibrakov
Nov 24 '18 at 6: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 6:05





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 6: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 3:20







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 3:20














1 Answer
1






active

oldest

votes


















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.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455576%2freturn-random-values-from-a-stack-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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.






    share|improve this answer






























      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.






      share|improve this answer




























        1












        1








        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 24 '18 at 6:17

























        answered Nov 24 '18 at 6:09









        Azat IbrakovAzat Ibrakov

        4,10271530




        4,10271530
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455576%2freturn-random-values-from-a-stack-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Futebolista

            Feedback on college project

            Albești (Vaslui)