使用堆栈类的非递归函数

问题描述 投票:0回答:1

enter image description here .

def F2(n): if n >= 6: F2(n / 3) F2(2 * n / 3) print(n)
你能帮我使用Python中的堆栈将这个递归函数转换为非递归函数吗?我已经尝试了两个小时但仍然卡住了。 Stack类有3个基本函数:isEmpty、pop和push。

python recursion stack
1个回答
0
投票
尝试这样:

def F2(n): stack = [] # create a stack to store values of n stack.append(n) while stack: cur = stack.pop() # get the top element from stack if cur >= 6: stack.append(2 * cur / 3) stack.append(cur / 3) print(cur)
    
© www.soinside.com 2019 - 2024. All rights reserved.