4

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?

2 Answers 2

6

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. What a beautiful solution. Thanks.
1

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

1 Comment

That is also nice. Yet considerably slower.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.