Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good pythonic way to map bits to characters in python?

Tags:

python

the_map = { 1:'a',0:'b'}

Now to generate, 8 patterns of a and b , we create 8 bit patterns:

>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]
# 001,010,011....111

How to map the bits to characters 'a' and 'b' , to receive output like :

['aaa','aab','aba'.......'bbb']

I am looking for an efficient one liner. My approaches using translate or format seem a bit inefficient to me:

>>> import string
>>> [bin(x)[2:].zfill(3).translate(string.maketrans('01','ab')) for x in xrange(8)]
['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
like image 745
DhruvPathak Avatar asked Dec 05 '25 07:12

DhruvPathak


2 Answers

I think you are looking for product:

>>> from itertools import product
>>> [''.join(i) for i in product('ABC',repeat=3)]
['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'B
AC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA', 'CBB'
, 'CBC', 'CCA', 'CCB', 'CCC']
like image 74
Burhan Khalid Avatar answered Dec 06 '25 22:12

Burhan Khalid


Not a huge improvement besides readability, but I think new style formatting could be a better fit here:

>>> '{:0<3b}'.format(1).translate(string.maketrans('01', 'ab'))
'baa'
like image 38
icecrime Avatar answered Dec 06 '25 22:12

icecrime