我如何使组合列表的参数最多为我提供给算法的 7 个单词中的 5 个单词?

How do I make that the list of combinations has a parameter of max 5 words out of the 7 words that I gave to the algorithm?

在这段代码中,我有 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')

您只需要 itertools.permutations built-in 函数:

from itertools import permutations

result = list(permutations(array, 5))