Strings Of Two Letters And Fixed Length
I'm wondering how to generate a list of all possible two-letter strings of length 10 in Python. For example, the list would go: aaaaaaaaaa aaaaaaaaab aaaaaaaaba aaaaaaaabb ... ...
Solution 1:
from itertools importproductprod= [''.join(p) for p in product('ab', repeat=10)]
or if you just want to print it like in your example:
from itertools import product
for p in product('ab', repeat=10):
print(''.join(p))
See the documentation for itertools.product
Solution 2:
You can count from 0
to 2**10-1
, convert those numbers using bin
and replace 0/1 with a/b. Just pad the left side with 0's to the right length.
Solution 3:
defs(d):
if d:
for c in'ab':
for rest in s(d-1):
yield c + rest
else:
yield''printlist(s(10))
or
def x(d):
return ([ 'a' + q for q in x(d-1) ] +
[ 'b' + q for q in x(d-1) ]) if d else [ '' ]
print x(10)
Post a Comment for "Strings Of Two Letters And Fixed Length"