How to make this function general to create binary numbers? (many nested for loops) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to make this function general to create binary numbers? (many nested for loops) (/thread-27833.html) |
How to make this function general to create binary numbers? (many nested for loops) - dospina - Jun-23-2020 As you can notice, this function is designed to create binary numbers in order into a list of lists. It works for 4 digits and each for loop is responsible for modifying a certain position. I would like to modify it so I can use it for any number of digits, but I haven't found a way to do it as I have to add a for loop every time I want to add a digit. Thank you so much for your help. def Binarynum(): lista=[]; for i in range(2): for j in range(2): for k in range(2): for l in range(2): lista.append([i,j,k,l]); return lista; lista=Binarynum(); RE: How to make this function general to create binary numbers? (many nested for loops) - pyzyx3qwerty - Jun-23-2020 Do not use a semicolon in Python code - it isn't used at the end of every line RE: How to make this function general to create binary numbers? (many nested for loops) - bowlofred - Jun-23-2020 You could use the product function from itertools. >>> from itertools import product >>> list(product([0, 1], repeat=4)) [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]Just change the repeat value. RE: How to make this function general to create binary numbers? (many nested for loops) - dospina - Jun-23-2020 (Jun-23-2020, 03:51 PM)pyzyx3qwerty Wrote: Do not use a semicolon in Python code - it isn't used at the end of every lineI know, I just prefer to do it because every other language I code in, requires it. So I do it anyway. RE: How to make this function general to create binary numbers? (many nested for loops) - deanhystad - Jun-24-2020 How about a function that converts positive integers to lists of bits. def binary(number): bits = [] while number != 0: bits.insert(0, number % 2) number = number >> 1 return bitsIf you want to pad to some fixed length. def binary(number, pad=0): bits = [] while number != 0: bits.insert(0, number % 2) number = number >> 1 while len(bits) < pad: bits.insert(0, 0) return bitsYou could also use bin() and a list comprehension: def binary(number, pad=0): return [1 if bit == '1' else 0 for bit in bin(number)[2:]] |