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

zpqajqem  于 7个月前  发布在  Python
关注(0)|答案(1)|浏览(62)

使用代码生成文件

代码将返回两个文件与可能的组合!
最后一个文件是使用!
使用itertools生成可能的字母组合
连接元组到字符串
将输出Map到字符串
将输出写入文件
阅读生成的文件并删除不必要的空格
最后测试

文件: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')
ycl3bljg

ycl3bljg1#

假设你的问题是“为什么在文件数据中找不到'lida',而在文件数据中找到了'adil'?”答案是:因为你在任务中使用了错误的itertools函数(和/或误解了它的作用)。
combinations生成所有 unique 的元素,按照在输入iterable中的位置排序。因为你的输入iterable是有序的,所以你的输出元素也总是有序的; 'abcd'将存在,但'abdc'不会存在,因为d在输入中位于c之后(不存在abcd * 的排序,除了 * 'abcd')。如果您想包含所有各种排列,(因此'adil''lida'都出现在输出中),您需要itertools.permutations,而不是itertools.combinations。(所以'aaaa'是一个可能的输出),如果只需要按照combinations的唯一输出,则需要combinations_with_replacement,或者如果需要按照permutations的所有排序,则需要product(通过关键字传递repeat参数)。
不过要注意的是,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试图同时容纳所有排列。

相关问题