创建一个 txt 文件并在 txt 文件中添加列表的所有组合

Creating a txt File and adding all combinations of a list in a txt file

我想知道如何 return 列表的每个输出都破解成文本文件

例如,如果我得到:

abandon able ability

我希望将此(我称之为破解输出)输出到文本文件中。等等

def generate(arr, i, s, len):

    # base case
    if (i == 0): # when len has
                # been reached
    
        # print it out
        print(s)
        return
    
    # iterate through the array
    for j in range(0, len):

        # Create new string with
        # next character Call
        # generate again until
        # string has reached its len
        appended = s + arr[j]
        generate(arr, i - 1, appended, len)

    return

# function to generate
# all possible passwords
def crack(arr, len):

    # call for all required lengths
    for i in range(3 , 5):
        generate(arr, i, "", len)
    
# Driver Code
arr = ["abandon ","ability ","able ","about ","above ","absent "]
len = len(arr)
crack(arr, len)

从一组 5 项中取出 3 项的排列与组合的演示

在数学中,单词组合和排列具有特定且不同的含义。对于 2048 个项目,一次取 12 个:

  1. permutation 表示 12 项的顺序很重要,结果将是 5.271537971E+39 项。
  2. combination表示12项的顺序不重要,结果为'1.100526171E+31'项。
  3. 使用 `itertools' 库在 python 中很容易对组合和排列进行编程。但是,这两个程序都需要很长时间才能 运行.
import itertools

lower_case_letters = ['a', 'b', 'c', 'd', 'e']

print(' Permutations '.center(80, '*'))
permutations = []
sample_size = 3
for unique_sample in itertools.permutations(lower_case_letters, sample_size):
    permutations.append(unique_sample)
    print(f'{len(permutations)=} {unique_sample=}')

f = open('permutations_results.txt', 'w')
for permutation in permutations:
    f.write(", ".join(permutation) + '\n')
f.close()

print(' Combinations '.center(80, '*'))
combinations = []
for unique_sample in itertools.combinations(lower_case_letters, sample_size):
    combinations.append(unique_sample)
    print(f'{len(combinations)=} {unique_sample=}')

f = open('combinations_results.txt', 'w')
for combination in combinations:
    f.write(", ".join(combination) + '\n')
f.close()