1

I have the following charset:

qwertyiopnmjk013

I want to generate all possible strings of 6 characters and also all with 7 characters noting that each letter only appears once in the same generated string.

Which is the best form to do it in python? Any example?

Right now I'm copying the charset to another variable and then I start generating picking letters and removing them from the charset then moving forward but I think that's not the best way..

Pau Muñoz
  • 67
  • 1
  • 6
  • This is not a duplicate. Since he is asking for "all possible strings" he means permutations, not combinations as the title suggests. – Imran Dec 14 '17 at 18:27

4 Answers4

3

use itertools:

    import itertools
    myStr = "qwertyiopnmjk013"
    chars = list(myStr)
    for comb in itertools.combinations(chars, 6):
        print comb
Austin A
  • 566
  • 2
  • 15
2

The question is somewhat ambiguous, but here's all the parts. First, just to get combinations:

import itertools
source = "qwertyiopnmjk013"
map(''.join, itertools.combinations(source, 6))

Now, if you want no repeated letters even if your source string contains duplicates, then fix your source string first with:

source = ''.join(set("qwertyiopnmjk013"))

If you also want each of the combinations re-arranged in each order, then you're dealing with permutations, not combinations. To get both into a nice list:

reduce(lambda x, y: x + y, map(lambda x: map(''.join, itertools.permutations(x)), itertools.combinations(source, 6)))

You should note that at this point you're getting into 10s of millions of strings; hope you have a fast machine.

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
  • `import itertools print(map("".join, itertools.combinations("aaaaaaa", 6)))` => `['aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa']` Task: noting that *each letter only appears once in the same generated string*. I think the issue is in considering same letters in the original string as "different". I admit the question can be read differently and there's some ambitiously. – Axalix Dec 14 '17 at 01:00
0

You can use itertools.combinations:

import itertools
s = "qwertyiopnmjk013"
final_letters = [''.join(b) for b in [i for i in itertools.combinations(s, 6)]+[i for i in itertools.combinations(s, 7)] if len(set(b)) == len(b)]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

Since you say:

I want to generate all possible strings of 6 characters and also all with 7 characters noting that each letter only appears once in the same generated string.

I assume you mean permutations, not combinations.

In your example you don't have repeated characters, but in case you do you can convert the string to a set first.

from itertools import permutations

def permute_string(s, n):
    return map(lambda x: ''.join(x), permutations(set(s)))

my_string = 'qwertyiopnmjk013'
six_chars = list(permute_string(my_string, 6))
seven_chars = list(permute_string(my_string, 7))
Imran
  • 12,950
  • 8
  • 64
  • 79