【问题标题】:Python recursive permutation by integer and returns a set of tuplesPython按整数递归排列并返回一组元组
【发布时间】:2022-01-14 20:55:55
【问题描述】:

首先,我搜索了许多网站,并花了很多时间寻找实现这一特定要求的方法。仅举几例,来自 SO 的 thisthis 以及来自外部站点的许多其他人。

这个要求很容易理解。

我不能使用import,只能使用递归来完成这个任务。仅此功能必须能够自行解决问题。不允许使用辅助函数。

我必须用这个定义写一个函数:

def permutation(n: int) -> set[tuple[int]]:

调用permutation(3)时的预期结果如下:

{(1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1 )}

我感到非常沮丧,以至于我无法在此提供任何有用的尝试。我试图为此想出一个解决方案,但想不出任何有用的东西。因此,我没有示例代码可以开始。

【问题讨论】:

  • 我猜你不允许在 permutation() 函数中定义辅助函数?
  • @rchome 不允许使用辅助函数。

标签: python algorithm recursion permutation


【解决方案1】:

这个想法是,如果您可以获得 n - 1 的每个排列的列表,您可以在这些排列结果的每个点之间插入 n

def permutation(n):
    if n == 0:
        # base case
        return {()}
    result = set()
    for x in permutation(n - 1):
        for i in range(n):
            # insert n in position i in the permutation of all of the lesser numbers
            result.add(x[:i] + (n,) + x[i:])
    return result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-25
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2020-10-19
    相关资源
    最近更新 更多