[英]Finding All permutations of a list when given a function that returns the next permutation of a list
In my assignment this week I was asked to write a python script that takes a number n and returns all permutations of [0,1,2,...,n-1].在本周的作业中,我被要求编写一个 Python 脚本,该脚本采用数字 n 并返回 [0,1,2,...,n-1] 的所有排列。 So far I have written a script that takes a list and returns the next permutation of the list.到目前为止,我已经编写了一个脚本,它接受一个列表并返回列表的下一个排列。 I am looking for ideas on how I can write the script based on what I've written so far.我正在寻找关于如何根据我目前所写的内容编写脚本的想法。
def next_permutation(p):
a = len(p)
i = a -2
while i >= 0 and p[i] >= p[i+1]:
i = i-1
if i == -1:
return []
j = i+1
while j < a and p[j] >= p[i]:
j += 1
j-=1
p[i], p[j] = p[j], p[i]
k = i + 1
l = a - 1
while k < l:
p[k], p[l] = p[l], p[k]
k += 1
l -= 1
return p
EDIT: this is the code that returns the next permutation of a list.编辑:这是返回列表下一个排列的代码。 I wrote this entirely based on the instruction provided by my instructor.我完全根据导师提供的说明写了这篇文章。
Since you want to have all the permutations of a list with numbers from 0 to n-1, you already have clear steps that you need to take:由于您希望拥有从 0 到 n-1 的数字的列表的所有排列,因此您已经有了需要采取的明确步骤:
This can be easily done with the in-built range()
function since it is mostly used for exactly that purpose:这可以通过内置的range()
函数轻松完成,因为它主要用于该目的:
This is a versatile function to create iterables yielding arithmetic progressions.这是一个多功能函数,用于创建产生算术级数的迭代。
Math tells us that having N elements, there will be N!数学告诉我们,有 N 个元素,就会有 N! different permutations of those elements, wher !这些元素的不同排列,哪里! means factorial.表示阶乘。 We can import factorial function from math module which would quickly allow us to calculate the amount of permutations your list will have:我们可以从 math 模块导入阶乘函数,这将允许我们快速计算您的列表将具有的排列数量:
from math import factorial
print(factorial(4)) # 24
next_permutation(p)
that you already wrote that many times and yield each and every permutation.调用您已经多次编写的函数next_permutation(p)
并产生每个排列。To return something more than once from a function, you can use yield insted.要从函数中多次返回某些内容,您可以使用yield insted。
With these steps in mind, you can create something similar to this:记住这些步骤后,您可以创建类似于以下内容的内容:
def all_permutations(n):
# Constructing a list that contains all numbers from 0 to n-1
integer_list = list(range(n))
# Calculating the amount of permutations such list would have
permutation_count = factorial(n)
# Output that many permutations
for _ in range(permutation_count):
yield integer_list
integer_list = next_permutation(integer_list)
This generator function will yield all permutations of a list containing numbers from 0 to n-1 which is exactly what you need.此生成器函数将生成包含从 0 到 n-1 的数字的列表的所有排列,这正是您所需要的。
To create a list that would contain all of the permutations you can write something simple like:要创建一个包含所有排列的列表,您可以编写一些简单的内容,例如:
n = 4
all_permutations = list(all_permutations(n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.