组合递归算法

编程入门 行业动态 更新时间:2024-10-23 17:26:42
本文介绍了组合递归算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Python中,我需要编写一个递归函数来计算列表中所有长度 n的可能组合,而无需导入 itertools 等之类的东西。

所以我到目前为止是:

如果n == 0 : return [[]] elif lst == []: return [] else: rest = subsets(lst [1:],n- 1)首先进入下一个:#遍历某些内容? return lst [0] + rest#添加一些内容?

我似乎对递归调用的工作方式缺乏了解,有人可以向我解释一下吗?

解决方案

在缺少必需的输出规范的情况下,我们可以编写一些伪代码,如下所示:

def组合(sub,data_set,items_needed):如果您不需要,则为data_set中的项目返回sub :将项目追加到data_set的子 #pop()项目中? 减少items_needed#再增加一个,因此我们需要少一个组合(new_sub,data_set,items_needed)

poping()与否(取决于是否需要子集中的唯一项)。

如果您说不想要[a,b]和[b,a]都需要跟踪最后添加的项的索引,以便仅添加新项以创建新组合。

def组合(子,数据集,索引,still_needed):如果不需要,返回范围内的i的(index,len (data_set)):将data_set [i]追加到sub 减少still_needed 组合(sub,data_set,index + 1,still_needed)

I need to write a recursive function that calculates all the possible combinations of length "n" in a list, in Python, without importing anything like itertools etc.

So what I have so far is:

if n == 0: return [[]] elif lst == []: return [] else: rest = subsets(lst[1:], n-1) for next in lst: # Loop through something? return lst[0] + rest #Add something?

I seem to be lacking an understanding of how the recursive calls work, can someone explain this to me?

解决方案

In the absence of the required output specifications, we could write some pseudo-code like this:

def combinations(sub, data_set, items_needed): if you dont need, return sub for item in data_set: append item to sub #pop() item from data_set? decrease items_needed # added one more, so we need one less combinations(new_sub, data_set, items_needed)

Where poping() or not will depend on you wanting (or not) unique items in the subset.

If you say you don't want both [a, b] and [b, a] you would have to also keep track of the index of the last item added, in order to only add new items to create new combinations.

def combinations(sub, data_set, index, still_needed): if you dont need any, return for i in range(index, len(data_set)): append data_set[i] to sub decrease still_needed combinations(sub, data_set, index+1, still_needed)

更多推荐

组合递归算法

本文发布于:2023-11-30 01:29:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648266.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   组合   算法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!