TypeError: can only concatenate str(not "NoneType") to str error using stack to reverse string

Asked 2 years ago, Updated 2 years ago, 18 views

I'm a Python beginner.I have a few questions about the code listed below.

  • reverse=reverse+stack.pop() appears to have the following error:

    TypeError: can only concatenate str(not "NoneType") to str
    
  • Why do you use stack.size() in while stack.size()?
    Does this mean that the character "Hello" is repeated for a few minutes (5 times)?
    Also, do you mean stack.size() until the contents are gone?

There appears to be a problem with reverse=reverse+stack.pop() and the following error appears:

TypeError: can only concatenate str(not "NoneType") to str

Why do I use stack.size() in while stack.size():?
Does this mean that the character "Hello" is repeated for a few minutes (5 times)?
Also, do you mean stack.size() until the contents are gone?

Code of interest:

 class Stack:
    def__init__(self):
        self.items = [ ]
    def push (self, item):
        self.items.append(item)
    def pop(self):
        self.items.pop()
    def size (self):
        return len(self.items)

stack = Stack()

for c in "Hello":
    stack.push(c)

reverse=""

while stack.size():
    reverse=reverse+stack.pop()

print(reverse)

python

2022-09-30 19:40

1 Answers

The first answer is def pop(self): return missing.
The following modifications are expected to work as intended.

Before: self.items.pop()
Corrected: return self.items.pop()

The second answer pops one end of the array every time you call pop(), so as you might expect, "Until the stack disappears and the return value of stack.size() is zero."


2022-09-30 19:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.