I would like to know how in Python I can iterate through a set of conditions.
So a short progression would be:
1a
1b
1c
...
1aa
1ab
1ac
...
2aaa
2aab
2aac
etc.
A horrible example that can do the first two is
##Loop through 1a-z0-9
start = '1'
l = 97
while l < 123:
num = start
num += chr(l)
print num
l += 1
l = 48
while l < 58:
num = start
num += chr(l)
print num
l += 1
I found itertools but can't find good examples to go off of.
You can do this using itertools.product
and itertools.chain
. First define strings of the numbers and letters:
numbers = '0123456789'
alnum = numbers + 'abcdefghijklmnopqrstuvwxyz'
Using itertools.product
, you can get tuples with the characters for the strings of various length:
len2 = itertools.product(numbers, alnum) # length 2
len3 = itertools.product(numbers, alnum, alnum) # length 3
...
Chain the iterators for all the lengths together, joining the tuples into strings. I'd do it with a list comprehension:
[''.join(p) for p in itertools.chain(len2, len3, len4, len5, len6)]
I would go with product function from itertools.
import itertools
digits = '0123456789'
alphanum = 'abcdef...z' + digits # this should contain all the letters and digits
for i in xrange(1, 6):
for tok in itertools.product(digits, itertools.product(alphanum, repeat=i)):
# do whatever you want with this token `tok` here.
You can think of this problem in base 26 (Ignoring the first number, we will put this in a separate case.) So with the letters we want to range from 'a' to 'zzzzz' in the base 26 would be 0 and (26,26,26,26,26) = 26 ^ 0 + 26 + 26^2 + 26^3 + 26^4 + 26^5. So now we have a bijection from numbers to letters, we just want to write a function that takes us from a number to a word
letters = 'abcdef..z'
def num_to_word( num ):
res = ''
while num:
res += letters[num%26]
num //= 26
return res
Now to write our function that enumerates this
def generator():
for num in xrange(10):
for letter_num in xrange( sum( 26 ** i for i in xrange( 6 ) ) + 1 ):
tok = str(num) + num_to_word( letter_num )
yield tok
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With