I am having an issue in using the stack reverse method. The first test case works but the data is not deleted and it messes up the next text case.
EDIT: My IDE is Google Colab.
**OUTPUT:**
Stack Before: -2 0 1 4 5
Stack After: 5 4 1 0 -2
Stack Before: 1 2 3 4 5 6
Stack After: 5 4 1 0 -2 6 5 4 3 2 1
Stack Before: a b c
Stack After: 5 4 1 0 -2 6 5 4 3 2 1 c b a
Stack Before: 8 -2 55 12 -47 10
Stack After: 5 4 1 0 -2 6 5 4 3 2 1 c b a 10 -47 12 55 -2 8
class Stack:
def __init__(self, arr=[]):
self.stack = arr
def __len__(self):
return len(self.stack)
def __str__(self):
res = ''
for each in self.stack:
res = str(each) ' '
return res
def push(self, number):
self.stack.append(number)
def pop(self):
self.stack.pop()
return
def peek(self):
ele = self.stack[-1]
return ele
def reverse(self, res = None) :
if not res:
res = Stack()
if not self:
return
x = self.peek()
self.pop()
res.push(x)
self.reverse(res)
return res
if __name__ == '__main__':
# Test Case 01
# Stack ---> -2 0 1 4 5
# Expected Answer ---> -2 0 4 5
test1 = Stack([-2,0,1,4,5])
print(f'Stack Before: {test1}')
test1 = test1.reverse()
print(f'Stack After: {test1}\n')
# Test Case 02
# Stack ---> 1 2 3 4 5 6
# Expected Result ---> 1 2 3 5 6
test2 = Stack([1,2,3,4,5,6])
print(f'Stack Before: {test2}')
test2 = test2.reverse()
print(f'Stack After: {test2}\n')
# Test Case 03
# Stack ---> a b c
# Expected Result ---> a c
test3 = Stack(['a', 'b', 'c'])
print(f'Stack Before: {test3}')
test3 = test3.reverse()
print(f'Stack After: {test3}\n')
# Test Case 04
# Stack ---> 8 -2 55 12 -47 10
# Expected Result ---> 8 -2 55 -47 10
test4 = Stack([8, -2, 55, 12, -47, 10])
print(f'Stack Before: {test4}')
test4 = test4.reverse()
print(f'Stack After: {test4}')
CodePudding user response:
Thanks for your help @SUTerliakov. I had to reverse engineer the geeksforgeeks solution though because my approach was wrong. I had to break the question in two seperate recursion problems to work.
def insertAtBottom(self, item) :
if self.isEmpty():
self.push(item)
return self
temp = self.peek()
self.pop()
self.insertAtBottom(item)
self.push(temp)
return self
def reverse(self) :
if self.isEmpty():
return self
temp = self.peek()
self.pop()
self.reverse()
self.insertAtBottom(temp)
return self