【问题标题】:Python - how to set limit of chars in result of permutation?Python - 如何在排列结果中设置字符限制?
【发布时间】:2020-11-06 04:09:19
【问题描述】:

我发现there 如何在 python 中对一些字符进行排列。但是我将其他字符添加到字符串中,现在当我运行代码时,我看到 long of 26 chars 的组合。 我想创建从字符串的所有字符只有10个字符的组合。 我在哪里可以重写它? 谢谢

def toString(List): 
    return ''.join(List) 
  

def permute(a, l, r): 
    if l==r: 
        print (toString(a))
    else: 
        for i in range(l,r+1): 
            a[l], a[i] = a[i], a[l] 
            permute(a, l+1, r) 
            a[l], a[i] = a[i], a[l] # backtrack 
string = "abcdefghijklmnopqrstuvwxyz"
n = len(string) 
a = list(string) 
permute(a, 0, n-1) 

【问题讨论】:

    标签: python string char permutation limit


    【解决方案1】:
    from itertools import permutations  
    
    p = permutations(string, 10)  
    

    但是,这将为您提供 5311735 个结果,这需要大量时间和内存。


    更新以获取字符串:

    from itertools import permutations
    out = list(map("".join, permutations('abcde', 4)))
    print(out)
    
    

    https://repl.it/@LukeStorry/62935781

    【讨论】:

    • 只有这个:? from itertools import permutations string = "abcdefghijklmnopqrstuvwxyz" p = permutations(string, 10) print(p)
    • 是的,但它永远不会完成运行,因为排列太多了。
    • 我在输出中看到:
    • 是的,permutations 对象可以被打印出来,但它还没有被评估。要获得任何有用的信息,您必须使用 list 将其转换为列表(需要很长时间)或 map 加入它们,如下所示:list(map("".join, itertools.permutations('1234'))) 请参阅 stackoverflow.com/questions/8113684/…
    • 我运行:from itertools import permutations list(map("".join, itertools.permutations('1234'))) 现在我看到 list(map("".join, itertools.permutations('1234'))) builtins.NameError: name 'itertools' is not defined 但是 intertools 被导入了...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多