Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create list of binary strings (Python)

I have a directed Multigraph and would like to identify the nodes with a binary string representing the coordinates of each node.
How can I build a list of these coordinates depending on the dimension of the multigraph?

Also the order of the coordinates is relevant. The first number is zero, then all numbers with one 1 in them, then all numbers with two 1s in them and so on. All these groupings of numbers have to be in reversed lexicographic order.

An example:

n = 3
bin_str = [000, 100, 010, 001, 110 101, 011, 111]

Is there a clever way to do this?

like image 645
sebastian Avatar asked Oct 23 '25 09:10

sebastian


1 Answers

You could use itertools.product:

from itertools import product
n = 3
# generate product in reverse lexicographic order
bin_str = [''.join(p) for p in product('10', repeat=n)]
# ['111', '110', '101', '100', '011', '010', '001', '000']    
# sort by number of ones
bin_str.sort(key=lambda s: s.count('1'))
# ['000', '100', '010', '001', '110', '101', '011', '111']
like image 135
mata Avatar answered Oct 26 '25 10:10

mata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!