为什么Python不能生成给定字母的所有可能组合?

问题描述 投票:0回答:1

生成文件的使用代码

代码将返回两个具有可能组合的文件!

最终文件就是要使用的!

使用 itertools 生成可能的字母组合

将元组连接到字符串

将输出映射到字符串

将输出写入文件

读取生成的文件并删除不必要的空格

终于测试了

文件:test.py

    #using itertools generating possible combinations of letters given below and writing it to a file

    from itertools import combinations

    a = "lida"
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]

    def Combinations(iterable, size):
        result = combinations(iterable, size)
        #joining tuple to string
        def join_tuple_string(strings_tuple) -> str:
            return ' '.join(strings_tuple)
        #maping output to string
        output = map(join_tuple_string, result)

        end = list(output)
        #writing the output to a file 
        with open('file.txt', 'w') as e:
            e.write(str(end))

    Combinations(letters, 4)
    #Reading the generated file and removing uncessary spaces

    with open('file.txt', 'r') as e:
        a = e.read()

        for i in range(len(a)):
            list = a[i]
            b = list.replace(' ', '')
            with open('final.txt', 'a') as f:
                f.write(b)
# finally Testing
with open('final.txt', 'r') as r:
    file = r.read()

    if 'adil' in file:
        print('present')

    if 'lida' in file:
        print('present')

    else:
        print('not present')
python python-3.x list code-generation python-itertools
1个回答
2
投票

假设您的问题是“为什么在文件数据中找不到

'lida'
,而
'adil'
却存在?”答案是:因为您在任务中使用了错误的
itertools
函数(和/或误解了它的作用)。

combinations
生成所有 unique 子序列,按输入可迭代中的位置排序。由于您的输入可迭代是按排序顺序排列的,因此您的输出元素也将始终按排序顺序排列;
'abcd'
将存在,但
'abdc'
不会存在,因为
d
在输入中出现在
c
之后(
a
b
c
d
除了
'abcd' 没有顺序) 
将存在)。如果您想包含所有各种排列(因此
'adil'
'lida'
都出现在输出中),您需要
itertools.permutations
,而不是
itertools.combinations
。同样,如果您需要一个能够重复的字母(因此
'aaaa'
是可能的输出),如果仅需要按照
combinations_with_replacement
combinations
(带有
product)的唯一输出,则需要 
repeat
 
参数通过关键字传递)如果您希望所有排序都按照
permutations

但请注意,对于 permutations,输出数量会变得

很多
;我强烈建议不要尝试将它们全部存储在内存中。只需将
permutations
对象和
write
逐个循环即可,例如:

with open('file.txt', 'w') as e:
   perms = map(''.join, permutations(iterable, size))   # map(''.join, ...) is an efficient way to change an iterable of tuples of str to single strs
   file.write(f'[{next(perms)!r}')  # Write open bracket and pull initial value
   # Iterate over remaining values
   for perm in perms:
       file.write(f',{perm!r}')  # Write comma and new value
   file.write(']')  # Write close bracket

它仍然会在文件中生成合法的

list
文字,并避免添加您首先试图避免的任何空格,所有这些都不会破坏您的 RAM 试图同时保存所有排列。

© www.soinside.com 2019 - 2024. All rights reserved.