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)
cede
Stack [0, 1, 2, 3, 4]
Stack [4, 3, 2, 1, 0]
Usted podría incluso haga un poco de fantasía usando el hecho de que el cierre mantiene el parámetro stack
de flip_stack
en el alcance de la función recursiva, por lo que no necesita que sea un parámetro para la función interna. p.ej.
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())
O, deshacerse de todos los parámetros de la función recursiva, y su marco de pila de subprocesos se lo agradecerán:
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
¿Tiene que ser recursiva? –
Sí. Tiene que ser recursivo. – isal
Esto suena como una pregunta de tarea. Si es así, debe agregar una etiqueta de 'tarea' –