Explain - binary number - 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: Explain - binary number (/thread-21607.html) |
Explain - binary number - RavCOder - Oct-07-2019 Hi, I ask if there is someone could be explain this code that I found and why it was used this solution,because I didn't find nothing on Internet , only a fucntion called bin(). This program should be print the max rappresentation of binary number ,passed before in number with base 10 and then converted in binary number. 5 n = int(input()) 6 max_one_count = 0 7 one_count = 0 8 9 while n != 0: 10 factor = n // 2 11 remainder = n - 2 * factor 12 n = factor 13 if remainder == 1: 14 one_count += 1 15 max_one_count = max(max_one_count, one_count) 16 else: 17 one_count = 0 18 19 print(max_one_count)Regards, RavCoder RE: Explain - binary number - perfringo - Oct-07-2019 I think that intentation is not correct. I assume that this is for counting consecutive '1' in binary number and finding longest consecutive run (max_one_count). Same result can be achieved by 'convert int to binary, split on zeros, find largest element and find it's length' >>> n = 3 # 0b11 >>> len(max(format(n, 'b').split('0'))) 2 RE: Explain - binary number - Gribouillis - Oct-07-2019 See also this page in the python wiki, especially the functions bitLenCount() and bitCount() with prestigious references to Kernighan and Ritchie and Knuth...
|