【发布时间】: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