In this code I have 7 words and when I run the file I get all possible combinations with the same word count of the list but I want it to give me all combinations with the same list of words with a max word count of 5. Can you please help me out on this?
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)
As you see here I have given the list array 7 words. But the problem is that when I run the file it gives me all combinations of the length of array.
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')
CodePudding user response:
You just need the itertools.permutations
built-in function:
from itertools import permutations
result = list(permutations(array, 5))