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)
Wydajność:
daje
Stack [0, 1, 2, 3, 4]
Stack [4, 3, 2, 1, 0]
Możesz nawet można sobie wyobrazić, wykorzystując fakt, że zamknięcie zachowuje parametr stack
w zakresie funkcji rekursywnej, więc nie jest konieczne, aby był parametrem funkcji wewnętrznej. na przykład
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())
Albo pozbyć się wszystkich parametrów na funkcji rekurencyjnej, a wątek stos ramka dziękuję:
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
Czy to ma być rekurencyjne? –
Tak. Musi być rekurencyjny. – isal
To brzmi jak zadanie domowe. Jeśli tak, dodaj tag "praca domowa" –