w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
counting in bits function

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. :-)





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.