简体   繁体   中英

Python - Algorithm to generate all possible arrays of ones and zeros of a given length

My goal is to come up with an array of all possible bit combinations of length n. For example, if n = 3, the target answer set should look like

000,
001,
010,
100,
011,
101,
110,
111

I've found the algorithmic solution , by I have completely no experience in iterators and C++ in general. Could someone give a hint how to rewrite the next function in python?

>>> import itertools
>>> result = ["".join(item) for item in itertools.product("01", repeat=3)]
>>> print result
['000', '001', '010', '011', '100', '101', '110', '111']

Without itertools: print the numbers from 0 to 2 ** n in base 2 and pad them with zeros:

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

Note that this leads to a much simpler solution in any language. All you need is a function to convert from base ten to base two. Then, for each number from 0 to 2 ** n , you convert it to base 2 and print or store the conversion.

To convert x to base two, divide it by 2 until it reaches 0 and keep track of the remainders. The list of remainders, in reverse order, is x in base 2:

x = 13
13 / 2 = 6 remainder 1
 6 / 2 = 3 remainder 0
 3 / 2 = 1 remainder 1
 1 / 2 = 0 remainder 1

=> 13 in base 2 = 1101
import itertools

#Possible characters
n = [0, 1]
#Asking required length
l = int(input("length: "))
#Putting all possibilities in list
r = list(itertools.product(n, repeat=l))

print(r)

Python always has a few handy libraries or functions to make complex things easy, and to make long taking work short.

In itertools.product() your first parameter should be an array of the characters of which you want all possibilities, and the second after the repeat-keyword is the length of the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM