-2

I have variable "n" which I use to give n bit count from the console, lets say n = 2, how do I make two separate arrays using loops that represents binary result: [00, 01, 10, 11] [00, 01, 10, 11] and then concatenate them to get result of:

          [00, 00] 
          [00, 01]
          [00, 10]
          [00, 11] then
          [01, 00] 
          [01, 01]
          [01, 10]
          [01, 11] etc.
ERM
  • 73
  • 7

1 Answers1

2

Do you want this ->

from itertools import product
l1=  ['00', '01', '10', '11']
l2 = ['00', '01', '10', '11'] 

result = list(product(l1,l2))

Output -

[('00', '00'),
 ('00', '01'),
 ('00', '10'),
 ('00', '11'),
 ('01', '00'),
 ('01', '01'),
 ('01', '10'),
 ('01', '11'),
 ('10', '00'),
 ('10', '01'),
 ('10', '10'),
 ('10', '11'),
 ('11', '00'),
 ('11', '01'),
 ('11', '10'),
 ('11', '11')]

Via nested for loop ->

result = []
for val1 in l1:
    for val2 in l2:
        result.append((val1,val2))

Via list comprehension -

result = [(val1,val2) for val1 in l1 for val2 in l2]

If items in the initial list are of type int then use a dict to map them to respective binary values-

from itertools import product
l1=  [0, 1, 10, 11]
l2 = [0, 1, 10, 11] 
map_dict = {0 :'00',1 :'01', 10 : '10', 11 :'11'}
list(map(lambda x: (map_dict[x[0]],map_dict[x[1]]) ,list(product(l1,l2))))
Nk03
  • 14,699
  • 2
  • 8
  • 22