0

I found there how to do permutation of some chars in python. But I add to string other chars and now when I run the code I see combinations with long of 26 chars. I would like to create combinations from all chars of string to only 10 chars. Where may I rewrite it? Thank you

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) 

1 Answer 1

1
from itertools import permutations  

p = permutations(string, 10)  

However, this will give you 5311735 results, which takes lots of time and memory.


UPDATE to get strings out:

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

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

7
  • Only this: ? from itertools import permutations string = "abcdefghijklmnopqrstuvwxyz" p = permutations(string, 10) print(p)
    – Mirek
    Jul 16, 2020 at 14:02
  • Yes, but it will never finish running, as there are far too many permutations. Jul 16, 2020 at 14:47
  • I see at output: <itertools.permutations object at 0x03BE90C0>
    – Mirek
    Jul 17, 2020 at 16:21
  • Yes, the permutations object can just be printed, but it won't have been evaluated yet. To get anything useful you either have to use list to turn it into a list (takes a long time) or map to join them, like so: list(map("".join, itertools.permutations('1234'))) See stackoverflow.com/questions/8113684/… Jul 17, 2020 at 21:43
  • I run: from itertools import permutations list(map("".join, itertools.permutations('1234'))) Now I see list(map("".join, itertools.permutations('1234'))) builtins.NameError: name 'itertools' is not defined but intertools was imported...
    – Mirek
    Jul 18, 2020 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.