#!/usr/bin/python
import random
lower_a = [\'a\', \'b\', \'c\', \'d\', \'e\', \'f\', \'g\', \'h\', \'i\', \'j\', \'k\', \'l\', \'m\', \'n\', \'o\', \'p\', \'q\', \'r
The pythonic way ;)
Print all combinations:
from itertools import combinations
symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
max_length = len(symbols)
for length in xrange(1, max_length + 1):
for word in map(''.join, combinations(symbols, length)):
print word
Even better, create an generator object which yields the combinations, so that one can decide later what to do with them without having to store 2 ** 62
strings (7.6040173890593902e+35
bytes) in memory.
from itertools import combinations, product
symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
max_length = len(symbols)
# generator of all combinations
def words1(chars=symbols, max_len=max_length):
for length in xrange(1, max_length + 1):
for word in map(''.join, combinations(symbols, length)):
yield word
# generator of all combinations allowing repetitions
def words1(chars=symbols, max_len=max_length):
for length in xrange(1, max_length + 1):
for word in map(''.join, product(*[symbols]*length)):
yield word
for word in words1():
#do something with word
print word
Both combinations
and product
, as well as many other functions, return iterators instead of lists in order to save memory:
>>> print combinations('0123456789',2)
>>> print list(combinations('0123456789',2))
[('0', '1'), ('0', '2'), ('0', '3'), ('0', '4'), ('0', '5'), ('0', '6'), ('0', '7'), ('0', '8'), ('0', '9'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('1', '6'), ('1', '7'), ('1', '8'), ('1', '9'), ('2', '3'), ('2', '4'), ('2', '5'), ('2', '6'), ('2', '7'), ('2', '8'), ('2', '9'), ('3', '4'), ('3', '5'), ('3', '6'), ('3', '7'), ('3', '8'), ('3', '9'), ('4', '5'), ('4', '6'), ('4', '7'), ('4', '8'), ('4', '9'), ('5', '6'), ('5', '7'), ('5', '8'), ('5', '9'), ('6', '7'), ('6', '8'), ('6', '9'), ('7', '8'), ('7', '9'), ('8', '9')]