6

Let's say there's n amount of entries, each of whom can take the value of 0 or 1. That means there's 2^n possible combinations of those entries. The number of entries can vary from 1 to 6.

How can you create each possible combination as a sequence of numbers (i.e. for n = 2: 00, 01, 10, 11), without resorting to a thousand IFs?

1

5 Answers 5

17

You can achieve that just by printing the numbers 0..2^n-1 in binary form.

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

1 Comment

Thanks, didn't think of that. Sometimes the answer is right in front of your nose yet you don't see it.
3

Might as well just use ints:

n = 5
for x in range(2**n):
  print ''.join(str((x>>i)&1) for i in xrange(n-1,-1,-1))

Crazy decimal to binary conversion lifted from this answer.

Output:

00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111

1 Comment

Sadly I don't understand a bit of Python, I mainly use Java. But I'll try to give it a shot. Thanks.
1

Generating the mth Lexicographical Element of a Mathematical Combination. LINK

And you must see this by DON KNUTH.(Generating all possible combinations.NOTE:C# code is also provide there.)

Comments

0

If possible values for each entries can be only 0 or 1, and you want just 0 and 1 combination, why don't you use the natural integers (in binary form) up to 2^(n-1)...as suggested above by Nick..and format those with '0' padding if you want string...

Comments

0

Or use itertools:

import itertools

for item in itertools.product((1, 0), repeat=4):
    print item

Note that the item is a tuple of 4 elements in this case.

Comments

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.