【问题标题】:permutation function does not return answers as a list置换函数不会将答案作为列表返回
【发布时间】:2018-12-04 16:05:35
【问题描述】:

我正在尝试获取列表中字符的所有可能排列。我需要它来返回列表中所有可能的烫发。列表的列表,其中列表的每个组件都是一个排列。似乎无法弄清楚它有什么问题。尝试使用列表,但没有任何帮助。尝试在不导入任何内容的情况下完成此操作。

代码:

def permutation(lst1, num_of_perms):
    if num_of_perms == len(lst1) - 1:
        print(lst1)

    for i in range(num_of_perms, len(lst1)):
        #  "removes" the first component of the list and returns all
        #  permutations where it is the first letter
        lst1[i], lst1[num_of_perms] = lst1[num_of_perms], lst1[i]
        #  swaps two components of the list each time.
        permutation(lst1, num_of_perms + 1)
        lst1[i], lst1[num_of_perms] = lst1[num_of_perms], lst1[i]
        #  swaps back before the next loop

我也愿意接受有关如何改进编码风格的任何提示。

【问题讨论】:

  • 谢谢,但我试图在没有 itertools 的情况下完成这项工作
  • 你没有返回任何东西;你只是在打印一个特定的排列。
  • 您的代码运行过低谷了吗?它应该在“def permutation”语句之后给出一个缩进错误
  • 它确实通过了,只有当我在这里上传代码时缩进才会改变。

标签: python python-3.x


【解决方案1】:

返回值和打印值之间是有区别的,尽管如果您只是从交互式解释器中运行函数可能会很棘手,因为它总是将函数的返回值打印到标准输出。

最简单的解决方法是将permutation 设为生成器函数,因为它只需将print 替换为yield。您需要在基本情况下生成列表的副本(否则,当您最终迭代返回值时,您将获得对当时 lst1 所指的任何内容的引用,而不是它所指的内容当你使用yield)。您还需要显式地从递归调用中产生值。

def permutation(lst1, num_of_perms):
    if num_of_perms == len(lst1) - 1:
        yield(lst1[:])

    for i in range(num_of_perms, len(lst1)):
        #  "removes" the first component of the list and returns all
        #  permutations where it is the first letter
        lst1[i], lst1[num_of_perms] = lst1[num_of_perms], lst1[i]
        #  swaps two components of the list each time.
        yield from permutation(lst1, num_of_perms + 1)
        lst1[i], lst1[num_of_perms] = lst1[num_of_perms], lst1[i]
        #  swaps back before the next loop

通过这些更改,您可以从生成器本身列出一个列表:

>>> list(permutation([1,2,3],0))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

或一次迭代一个排列

>>> for i, p in enumerate(permutation([1,2,3], 0)):
...   print("{}) {}".format(i, p))
...
0) [1, 2, 3]
1) [1, 3, 2]
2) [2, 1, 3]
3) [2, 3, 1]
4) [3, 2, 1]
5) [3, 1, 2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2020-10-10
    • 2020-10-04
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多