简体   繁体   中英

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?

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']

can also be done using recursion

def bin_list(n):
      if n == 0:
            #base case
            return ['']
      else:
            return [i + '0' for i in bin_list(n-1)] + [i + '1' for i in bin_list(n-1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM