Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Explain - binary number
#1
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
Reply
#2
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
See also this page in the python wiki, especially the functions bitLenCount() and bitCount() with prestigious references to Kernighan and Ritchie and Knuth...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  hex file to binary or pcap to binary baran01 1 5,630 Dec-11-2019, 10:19 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020