I have the following code:
dic = {}
bin_rep = [1 if digit == '1' else 0 for digit in bin(n)[2:]]
if len(bin_rep) < size_bin:
bin_rep += [0] * (size_bin - len(bin_rep))
# turn this into dictionnary - might all be done better?
for i in range(0, size_bin):
dic[self.p.get_agents()[i]] = bin_rep[i]
return dic
Essentially, I'm taking an number n, turning it into a list (its binary representation, potentially padded with 0 up to size_bin
), say:
[0 1 1 1 1 0 0 0 0 0 0]
From that padded list, I create a dictionary, where key==agent name and value==1
/0
, say:
{'a1':0, 'a2':1 ... 'an':0}
(The array as a whole corresponds to a team, the 0
/1
represents the inclusion of an agent into the team. So each team corresponds to a binary array which can be represented as an int
.)
The code works, using list and dictionary comprehension. However, would someone have a cleaner/smarter way to perform this? It's good if it's optimal, though not crucial, and would like to keep it readable.
I absolutely need to have the ultimate result into a dictionary because other parts of the code use that representation.
EDIT: using python 3.6