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)
sản lượng
Stack [0, 1, 2, 3, 4]
Stack [4, 3, 2, 1, 0]
Bạn thậm chí có thể có được một chút ưa thích bằng cách sử dụng thực tế rằng việc đóng giữ thông số stack
của flip_stack
trong phạm vi của hàm đệ quy, do đó bạn không cần nó là tham số cho hàm bên trong. ví dụ.
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())
Hoặc, thoát khỏi tất cả các thông số về chức năng đệ quy, và ngăn xếp khung chủ đề của bạn sẽ cảm ơn bạ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
Liệu nó phải được đệ quy? –
Có. Phải được đệ quy. – isal
Điều này nghe giống như một câu hỏi về bài tập về nhà. Nếu vậy, bạn nên thêm thẻ 'bài tập về nhà' –