Liondancer
Liondancer

Reputation: 16469

counting in bits function

I am trying to print the max number of bits (n) and also the max number those number of bits are able to represent. I feel as though the problem is in the x = x%2

input:

sortbit(3)

output:

000
111
000
111
000
111
000
111

expected output"

000
001
010
011
100
101
110
111

my code:

def sortbit(n):
    max_num = 2**n

    for x in range(0,max_num):
        stringy = []
        a = 0
        while a < n:
            a += 1
            x = x % 2
            if x == 0:
                stringy.insert(a,'0')
            else:
                stringy.insert(a,'1')
        t = ''.join(stringy)
        print t

Upvotes: 1

Views: 129

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1123360

You are turning any number into either 1 or 0 with x = x % 2. You may as well just print str(x % 2) * n.

You need to use integer division instead, and test separately for even or odd.

Even better, you could just append the output of the modulus test, as string, to stringy:

stringy.insert(0, str(x % 2))
x = x // 2

Demo with the code simplified a bit:

>>> def sortbit(n):
...     max_num = 2**n
...     for x in range(max_num):
...         stringy = []
...         for a in range(n):
...             stringy.append(str(x % 2))
...             x //= 2
...         print ''.join(reversed(stringy))
... 
>>> sortbit(3)
000
001
010
011
100
101
110
111

You could also bitshift the value; the >> operator moves the bits to the right for you by a given number of steps; x >> 1 shifts the bits in x one step over, essentially dividing by two.

You could also look into the bin() function (returns the value as a binary string, starting with 0b), and the format() function, together with the str.format() method, which lets you format values as binary strings as well using the b output format. Printing your values in a loop could be as simple as:

def sortbit(n):
    for i in range(2**n):
        print '{:0{}b}'.format(i, n)

Last but not least, you are simply producing the product of the digits 0 and 1, n times. You could express that with itertools.product() as well:

>>> from itertools import product
>>> for bits in product('01', repeat=3):
...     print ''.join(bits)
... 
000
001
010
011
100
101
110
111

but that could be seen as cheating. :-)

Upvotes: 2

Mark Tolonen
Mark Tolonen

Reputation: 177891

You've got answers for your specific code, so here's a solution using Python's format to print n digits of binary with the appropriate number of leading zeroes:

>>> def sortbit(n):
...  for i in range(2**n):
...   print '{0:0{1}b}'.format(i,n)
...
>>> sortbit(2)
00
01
10
11
>>> sortbit(3)
000
001
010
011
100
101
110
111

Upvotes: 2

6502
6502

Reputation: 114559

You should use x % 2 in the if, not assigning back to x

if x % 2 == 0:
  ...

also at each iteration you should move over to next bit, otherwise you're adding the same bit over and over:

x = x >> 1

Upvotes: 1

Related Questions