在這段代碼中,我有 7 個單詞,當我運行檔案時,我得到了串列中具有相同字數的所有可能組合,但我希望它為我提供具有相同單詞串列且最大字數為 5 的所有組合。可以請你幫我解決這個問題?
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)
正如你在這里看到的,我給了串列陣列 7 個單詞。但問題是,當我運行檔案時,它給了我陣列長度的所有組合。
if __name__ == "__main__":
array = ["abandon ","ability ","able ","about ","above ","absent ","absorb "]
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)
#print(permutations)
file = open('crack.txt', 'w') # Open a file to receive output
for permutaion in perms2:
text = " ".join(list(permutaion))
print(text)
file.write(text)
file.write('\n')
uj5u.com熱心網友回復:
您只需要itertools.permutations內置函式:
from itertools import permutations
result = list(permutations(array, 5))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439274.html
上一篇:從資料框列中提取唯一關鍵字和計數
