How to create all possible combinations from a string?

Asked

Viewed 214 times

-3

I tried to use

a = 'abcdefghijklmnopqrstuvwxyz'
itertools.product(a, repeat=4)

to create all possible words with 4 letters, but it seems to me that when the quantity is too large it doesn’t work properly.

Is there any alternative to dealing with high combinations?

The only solution I’ve thought of so far is to use Random.Choice to create a random word and use a filter to not choose repeated words

  • 1

    What is the error? The function appears to work perfectly.

  • 1

    Apparently you saw that the product did not return a list and assumed that "gave probledúsma because it is too big". Tip to be able to do cool things in programming: try and try. If you suspected that the problem was "ours," that’s a lot," you should have tried with a smaller set of data to see if it worked. Then I’d know that wasn’t the problem.

  • 1

    -1 : The question is bad, "Does not work correctly" is very vague. If edit and better elaborate the question (preferably with examples of the problem found) I withdraw my negative vote.

  • I found that the problem was in the IDE,she couldn’t show the complete list, so when I typed a random word it didn’t show up

2 answers

4

You are doing something else wrong - although the number of combinations is large, in my system itertools.product generated the 400,000+ possible combinations in this case in less than 0.1 second.

What do you call "not working properly"? Remember that itertools returns a tuple with the 4 letters, you have to make some other call to join the letters in a word:

In [73]: c = [''.join(b)  for b in itertools.product(a, repeat=4)]

In [74]: len(c)
Out[74]: 456976

In [76]: print(c[0:50])
['aaaa', 'aaab', 'aaac', 'aaad', 'aaae', 'aaaf', 'aaag', 'aaah', 'aaai', 'aaaj', 'aaak', 'aaal', 'aaam', 'aaan', 'aaao', 'aaap', 'aaaq', 'aaar', 'aaas', 'aaat', 'aaau', 'aaav', 'aaaw', 'aaax', 'aaay', 'aaaz', 'aaba', 'aabb', 'aabc', 'aabd', 'aabe', 'aabf', 'aabg', 'aabh', 'aabi', 'aabj', 'aabk', 'aabl', 'aabm', 'aabn', 'aabo', 'aabp', 'aabq', 'aabr', 'aabs', 'aabt', 'aabu', 'aabv', 'aabw', 'aabx']
  • should have all possible combinations of 4 letters right? but when I go to test a 4-letter word, many of them do not appear

  • have them all. How are you testing? The "in" operator can tell whether a word is present there or not.

  • found that the problem was in the IDE

2

The function product of itertools returns a eternal object. So, to access, you need to go through a loop iteration for, for example. See:

import string
import itertools

abc  = string.ascii_lowercase
prod = itertools.product(abc, repeat=4)

for i in prod:
    print(i)

The result (output) can be seen in this file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.