Home > other >  Recursive Sort for a Stack in Python
Recursive Sort for a Stack in Python

Time:08-09

I am learning recursion and am tasked with sorting an array. My study material is in Java and I am coding into Python myself. I made a Stack class with few common methods and a unique sort_s method that should use recursion to sort the Stack. I have a helper fucntion to execute the Induction step in the 'IBH-method'. My sort_s method is giving a name error. I suspect taking the function out of the class could solve the issue, but is there any way to keep the methods within the class. The error message and code is printed below. Thank you in advance for your help.

NameError
Traceback (most recent call last)
in ()
60 test.push(8)
61
---> 62 sort_s(test)
63 print(test)

NameError: name 'sort_s' is not defined

# Sort a stack using recursion

class Stack:
  def __init__(self, arr=[]):
    self.stack = []
    for ele in arr:
      self.stack.append(ele)

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

  def __str__(self):
    res = ''
    for each in self.stack:
      res  = str(each)   ' '
    return res

  def get_stack(self):
    return self.stack

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

  def pop(self):
    ele = self.stack[-1]
    self.stack.pop()
    return ele

  def tail(self):
    tail = self.stack[-1]
    print(tail)

  def sort_s(self, s: Stack):
    if len(s.stack) <= 1: # Base Condition
      return s.stack
    temp = s.pop() # Hypothesis
    sort_s(s.stack) 
    return self.ordered_insert(s.stack, temp) # Induction
    

  def ordered_insert(self, arr, temp):
    for i in range(len(arr)):
      if arr[i] > temp:
        arr.insert(i, temp)
        break
      elif arr[-1] < temp:
        arr.append(temp)
    return arr
  

if __name__ == '__main__':
  test = Stack([0, 5, 1])
  print(test)
  test.tail()
  test.push(3)
  y = test.pop()
  print(f'{10 y}')
  print(test)
  test.push(6)
  test.push(9)
  test.push(8)

  sort_s(test)
  print(test)

CodePudding user response:

Thanks to @DownloadPizza, I was able to correct the sort_s function.

def sort_s(self):
    if len(self.stack) <= 1: # Base Condition 
        return self.stack 
   temp = self.pop() # Hypothesis 
   self.sort_s() 
   return self.ordered_insert(self.stack, temp) # Induction 
  • Related