python找素数 递归_用于跟踪可删除素数的递归函数python3

我不打算为您调试代码,但我将尝试回答您遇到的具体问题:but I can't wrap my head around the recursive thinking necessary to

have it trace all the paths and put them neatly in a list:

要使递归函数将其结果收集到列表中,需要执行以下操作:def _myfn(data, res):

if (..recurse..):

return _myfn(data2, res + [item]) # item being the result of this iteration

else:

# terminal case

return res

def myfn(data):

return _myfn(data, [])

您可以将这些压缩为一个函数:

^{pr2}$

或者您可以使_myfn成为myfn的本地:def myfn(data):

def _myfn(data, res):

if (..recurse..):

return _myfn(data2, res + [item])

else:

# terminal case

return res

return _myfn(data, [])

当涉及到递归思维时,只需记住(1)始终处理基本情况;-)和(2)在每次递归中首先(i)生成所有可能的下一步步骤,(ii)然后在每个递归中递归。为(i)编写一个单独的函数通常会清除一些代码。在

作为一个递归函数的例子,该函数在二叉树中查找从根到叶的所有路径(稍微按教学法编码)--这就是您要做的:# tree = (root, left, right)

def all_paths(t):

leaf_paths = []

def _all_paths(t, res):

root, left, right = t

# calculate all next-steps

next_steps = [step for step in [left, right] if step]

if not next_steps:

# handle base case (found one solution)

leaf_paths.append(res + [root])

else:

# recurse

for step in next_steps:

_all_paths(step, res + [root])

_all_paths(t, [])

return leaf_paths

>>> all_paths( (2, (), ()) )

[[2]]

>>> all_paths(

... (2,

... (3, (), ()),

... (4, (), ())))

[[2, 3], [2, 4]]

这张图呢

LrG5Z.png>>> t = (

2,

(7,

(2, (), ()),

(6,

(5, (), ()),

(11, (), ()))),

(5,

(),

(9,

(4, (), ()),

())))

>>> print all_paths(t)

[[2, 7, 2], [2, 7, 6, 5], [2, 7, 6, 11], [2, 5, 9, 4]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值