My binary_list
is a list of strings of "000", "001", "010",....
I am trying to add into a dictionary the number of 1's in each string of bits.
he dictionary will be created with the size of n
for each number of 1's that appear in the string
I can't seem to append the string of bits to a list and then add it to the dictionary. When I run the code I get:
input: sortbits(3)
000
001
010
011
100
101
110
111
{0: [], 1: [], 2: []}
correct output is:
000
001
010
011
100
101
110
111
{0: [000], 1: [001, 010, 100], 2: [011,101, 110], 3: [111]}
my code:
def sortbit(n):
max_num = 2**n
binary_list = []
for x in range(0,max_num):
stringy = []
for a in range(n):
stringy.append(str(x%2))
x //= 2
print ''.join(reversed(stringy))
stringy_list = ''.join(reversed(stringy))
binary_list.append(stringy_list)
count_dict = dict.fromkeys(range(0,n+1))
for element in binary_list:
count = 0
value_list = []
for character in element:
if character == '1':
count += 1
for y in count_dict:
if y == str(count):
value_list.append(element)
count_dict[y] = value_list
print count_dict