Enumerator for alphabet in python

Given:
alphabet = ['a','b','c',...,'z']
I want python to list each combination (starting with 1 letter in 1000 words). For example (if I want every combination of a word of length 10), it should start as follows:

 [a,b,c,d...,z,aa,ab,ac,ad,ae,...,aaa,aba,aca,ada,...,aab,aac,aad,....,zzzzzzzzzz] 

How to do it?

+4
source share
4 answers

itertools.product is what you are looking for:

 import itertools max_length = 10 result = (''.join(word) for word in itertools.chain.from_iterable( itertools.product(alphabet, repeat = i) for i in range(1, max_length + 1))) 

To do this, you need to use a generator, because there are simply too many possible words (even at a length of 10) to be able to store them all in memory on a desktop computer.

+3
source

Try using product from itertools :

 from itertools import product result = [] for i in range(1, 5): alphabets = [alphabet] * i for x in product(*alphabets): result.append(''.join(x)) 

Yes, it works on my machine. But do not run it from 1000.

+1
source

Update after notice that you care about order

You need to use itertools.product() and itertools.product() over it:

 result = [] for r in range(1, 4): result.extend(''.join(i) for i in product(alphabet, repeat=r)) 

Simple check:

 >>> 'dog' in result True >>> 'god' in result True 

Or without a generator expression:

 for r in range(1, 4): for i in product(alphabet, repeat=r): result.append(''.join(i)) 

Tell about the madness

Each solution here cannot handle long words, which means that there are too many possible combinations (this is any mistake). I don't care if this implementation can only process words shorter than "epicalyx", while agf's answer can handle up to 10 letters.

This approach should only be used for small words.

"I want python to list each combination (from 1 letter word to, for example, 1000 word labels)" - This means the OP said.

No one in their right mind should even try to list all of these possibilities in this way, and anyone who thinks it is or tries to push that limit is crazy and should really take a look at ChessMaster's Comments .

+1
source

Two things to consider here:

  • itertools.product from range 1 to n, where n is the maximum word size, will give the desired result.
  • You must use a generator, otherwise you will soon run out of memory.

Here is one such implementation

 >>> def foo(somelist,n): return (''.join(x) for i in xrange(1,n+1) for x in itertools.product(somelist, repeat=i)) 

You can call the foo generator as follows

 >>> for i in foo(string.ascii_lowercase,10): print i, 
+1
source

Source: https://habr.com/ru/post/1403696/


All Articles