class Stack(object):
def __init__(self,items=[]):
self.stack = items
def is_empty(self):
return not self.stack
def pop(self):
return self.stack.pop()
def push(self,val):
self.stack.append(val)
def __repr__(self):
return "Stack {0}".format(self.stack)
def flip_stack(stack):
def flip_stack_recursive(stack,new_stack=Stack()):
if not stack.is_empty():
new_stack.push(stack.pop())
flip_stack_recursive(stack,new_stack)
return new_stack
return flip_stack_recursive(stack)
s = Stack(range(5))
print s
print flip_stack(s)
yields
Stack [0, 1, 2, 3, 4]
Stack [4, 3, 2, 1, 0]
You could even get a little fancy using the fact that the closure keeps the stack
parameter of flip_stack
in the scope of the recursive function, so you don't need it to be a parameter to the inner function. e.g.
def flip_stack(stack):
def flip_stack_recursive(new_stack):
if not stack.is_empty():
new_stack.push(stack.pop())
flip_stack_recursive(new_stack)
return new_stack
return flip_stack_recursive(Stack())
Or, get rid of all parameters on the recursive function, and your thread stack frame will thank you:
def flip_stack(stack):
new_stack = Stack()
def flip_stack_recursive():
if not stack.is_empty():
new_stack.push(stack.pop())
flip_stack_recursive()
flip_stack_recursive()
return new_stack