gpt4 book ai didi

How do I generate all permutations of a list?(如何生成列表的所有排列?)

转载 作者:bug小助手 更新时间:2023-10-25 16:50:58 24 4
gpt4 key购买 nike



How do I generate all the permutations of a list? For example:

如何生成列表的所有排列?例如:


permutations([])
[]

permutations([1])
[1]

permutations([1, 2])
[1, 2]
[2, 1]

permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

更多回答
优秀答案推荐

My Python Solution:

我的Python解决方案:



def permutes(input,offset):
if( len(input) == offset ):
return [''.join(input)]

result=[]
for i in range( offset, len(input) ):
input[offset], input[i] = input[i], input[offset]
result = result + permutes(input,offset+1)
input[offset], input[i] = input[i], input[offset]
return result

# input is a "string"
# return value is a list of strings
def permutations(input):
return permutes( list(input), 0 )

# Main Program
print( permutations("wxyz") )


def permutation(word, first_char=None):
if word == None or len(word) == 0: return []
if len(word) == 1: return [word]

result = []
first_char = word[0]
for sub_word in permutation(word[1:], first_char):
result += insert(first_char, sub_word)
return sorted(result)

def insert(ch, sub_word):
arr = [ch + sub_word]
for i in range(len(sub_word)):
arr.append(sub_word[i:] + ch + sub_word[:i])
return arr


assert permutation(None) == []
assert permutation('') == []
assert permutation('1') == ['1']
assert permutation('12') == ['12', '21']

print permutation('abc')


Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

输出:[‘ABC’,‘ACB’,‘BAC’,‘BCA’,‘CAB’,‘CBA’]



Using Counter

使用计数器



from collections import Counter

def permutations(nums):
ans = [[]]
cache = Counter(nums)

for idx, x in enumerate(nums):
result = []
for items in ans:
cache1 = Counter(items)
for id, n in enumerate(nums):
if cache[n] != cache1[n] and items + [n] not in result:
result.append(items + [n])

ans = result
return ans
permutations([1, 2, 2])
> [[1, 2, 2], [2, 1, 2], [2, 2, 1]]



def permuteArray (arr):

arraySize = len(arr)

permutedList = []

if arraySize == 1:
return [arr]

i = 0

for item in arr:

for elem in permuteArray(arr[:i] + arr[i + 1:]):
permutedList.append([item] + elem)

i = i + 1

return permutedList


I intended to not exhaust every possibility in a new line to make it somewhat unique.

我不打算在一条新的生产线上用尽所有的可能性,让它变得有点独特。



from typing import List
import time, random

def measure_time(func):
def wrapper_time(*args, **kwargs):
start_time = time.perf_counter()
res = func(*args, **kwargs)
end_time = time.perf_counter()
return res, end_time - start_time

return wrapper_time


class Solution:
def permute(self, nums: List[int], method: int = 1) -> List[List[int]]:
perms = []
perm = []
if method == 1:
_, time_perm = self._permute_recur(nums, 0, len(nums) - 1, perms)
elif method == 2:
_, time_perm = self._permute_recur_agian(nums, perm, perms)
print(perm)
return perms, time_perm

@measure_time
def _permute_recur(self, nums: List[int], l: int, r: int, perms: List[List[int]]):
# base case
if l == r:
perms.append(nums.copy())

for i in range(l, r + 1):
nums[l], nums[i] = nums[i], nums[l]
self._permute_recur(nums, l + 1, r , perms)
nums[l], nums[i] = nums[i], nums[l]

@measure_time
def _permute_recur_agian(self, nums: List[int], perm: List[int], perms_list: List[List[int]]):
"""
The idea is similar to nestedForLoops visualized as a recursion tree.
"""
if nums:
for i in range(len(nums)):
# perm.append(nums[i]) mistake, perm will be filled with all nums's elements.
# Method1 perm_copy = copy.deepcopy(perm)
# Method2 add in the parameter list using + (not in place)
# caveat: list.append is in-place , which is useful for operating on global element perms_list
# Note that:
# perms_list pass by reference. shallow copy
# perm + [nums[i]] pass by value instead of reference.
self._permute_recur_agian(nums[:i] + nums[i+1:], perm + [nums[i]], perms_list)
else:
# Arrive at the last loop, i.e. leaf of the recursion tree.
perms_list.append(perm)



if __name__ == "__main__":
array = [random.randint(-10, 10) for _ in range(3)]
sol = Solution()
# perms, time_perm = sol.permute(array, 1)
perms2, time_perm2 = sol.permute(array, 2)
print(perms2)
# print(perms, perms2)
# print(time_perm, time_perm2)
```


in case anyone fancies this ugly one-liner (works only for strings though):

如果有人喜欢这个难看的一行(但只适用于字符串):


def p(a):
return a if len(a) == 1 else [[a[i], *j] for i in range(len(a)) for j in p(a[:i] + a[i + 1:])]


def permutate(l):
for i, x in enumerate(l):
for y in l[i + 1:]:
yield x, y


if __name__ == '__main__':
print(list(permutate(list('abcd'))))
print(list(permutate([1, 2, 3, 4])))

#[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
#[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]


Solving with recursion, iterate through elements, take i'th element, and ask yourself: 'What is the permutation of rest of items` till no more element left.

用递归求解,迭代元素,取第i个元素,然后问问自己:‘其余项的排列是什么?’直到没有更多的元素。


I explained the solution here: https://www.youtube.com/watch?v=_7GE7psS2b4

我在这里解释了解决方案:https://www.youtube.com/watch?v=_7GE7psS2b4


class Solution:
def permute(self,nums:List[int])->List[List[int]]:
res=[]
def dfs(nums,path):
if len(nums)==0:
res.append(path)
for i in range(len(nums)):
dfs(nums[:i]+nums[i+1:],path+[nums[i]])
dfs(nums,[])
return res


In case the user wants to keep all permutations in a list, the following code can be used:

如果用户想要在列表中保留所有排列,可以使用以下代码:


def get_permutations(nums, p_list=[], temp_items=[]):
if not nums:
return
elif len(nums) == 1:
new_items = temp_items+[nums[0]]
p_list.append(new_items)
return
else:
for i in range(len(nums)):
temp_nums = nums[:i]+nums[i+1:]
new_temp_items = temp_items + [nums[i]]
get_permutations(temp_nums, p_list, new_temp_items)

nums = [1,2,3]
p_list = []

get_permutations(nums, p_list)



Alternatively you could also rotate

或者,您也可以旋转



def perm_rotate(elements):
if len(elements) <= 1:
yield elements
return

for _ in range(len(elements)):
for perm in perm_rotate(elements[1:]):
yield [elements[0]] + perm
elements = rotate(elements)

def rotate(numbers):
return [numbers[-1]] + numbers[: len(numbers)-1]


for Python we can use itertools and import both permutations and combinations to solve your problem

对于Python,我们可以使用迭代工具并导入排列和组合来解决您的问题



from itertools import product, permutations
A = ([1,2,3])
print (list(permutations(sorted(A),2)))

更多回答

Some explanation would improve this answer.

一些解释会改进这个答案。

Beautiful and simple!

又漂亮又简单!

.....but wrong.

……但是错了。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com