1

I am having a difficulty in finding a way to access some list elements that are represented on a binary access pattern. What I mean is:

Suppose that we have a binary number Bin of 4 digits: Bin = 0b0000 We also have a list (or set or tuple, does not matter) of same length as Bin, lets say: list = [A, B, C, D]

Now, I want to combinatory access the elements that are represented by 1 in Bin meaning that as the counter increments +1 on each loop if we are at Bin = 0b0101 (which means Bin = 10) then I want to access the corresponding indices, hence B and D elements in the list.

Same goes until the loop ends when Bin = 0b1111 or Bin = 15 where I finally access all elements of list A, B, C, D.

Thanks in advance.

4
  • 1
    do you mean a powerset? Commented Jul 6, 2014 at 21:45
  • @PadraicCunningham Yes since binary is 2^n where n is the length but how am I supposed to check the 1 in the number? Use an operator maybe? Commented Jul 6, 2014 at 21:47
  • 1
    Read this. Commented Jul 6, 2014 at 21:47
  • @jonrsharpe Great link. Its very compact this solution :) Commented Jul 6, 2014 at 22:09

2 Answers 2

1

This is a powerset generator used on the M.I.T 6.00x course.

def powerSet(items):
    n = len(items)
    for i in xrange(2**n):
        combo = []
        for j in xrange(n):  
            #print i,j,(i >> j) % 2 == 1 # uncomment to see the values through the loop
            # test bit jth of integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo
print list(powerSet([1,2,3,4]))
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]

if (i >> j) % 2 == 1 can also be written as if (i >> j) & 1

It uses the >> Bitwise Operator.

*x >> y Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.*

Sign up to request clarification or add additional context in comments.

2 Comments

There's a much neater implementation in the itertools recipes.
@jonrsharpe, it helped me learn about powersets and the how the >> operator worked, I know there are better implementations but this helped me a lot.
0

If you don't need the full power-set:

def bin_access(iterable, index):
    return [b for a,b in zip(reversed(bin(index)[2:]), iterable) if a=='1']

1 Comment

Could you add some explanation or comments? Thanks

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.