Python Forum
Need Help: Sort of Binary numbers based on 1's present
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need Help: Sort of Binary numbers based on 1's present
#1
Question:
1. Find the Binary numbers from the given list of Numbers .
2. sort on ascending order based on the no of 1's present
3. if no of 1's are same , then give preference to its decimal nos.
4. After sorting, convert to Decimal numbers and Display the output .
Reply
#2
what have you tried so far and what problem(s) you are not able to resolve?
Reply
#3
Enter total no of number : 3
Enter numbers:[ 0 ]: 9
Enter numbers:[ 1 ]: 6
Enter numbers:[ 2 ]: 7
Numbers in list are : [9, 6, 7]
9 1001 count ones are : 2
6 110 count ones are : 2
7 111 count ones are : 3

I am facing challenges how to sort binary nos based on counting no of 1's .
Reply
#4
Did you read my link? We need to see your code
Reply
#5
I can't read your link...

codes are :
#Binary conversion
cnt_num = int(input("Enter total no of number : "))
num = []

for i in range(cnt_num):
   print("Enter numbers:[",i,"]: ",end = '')
     
   num1 = int(input())
   num.append(num1)

print("Numbers in list are : ",num)



for j in range(len(num)):
   
   bin_num.append(bin(num[j])[2:])
   
   bits = bin_num[j].count('1')
   print(num[j],bin_num[j],' count ones are : ',bits)
#Need to write logic to sort the binary numbers based on counting no of 1's
Reply
#6
Read https://docs.python.org/3/howto/sorting.html
and especially the part about key argument.
you need to specify a key in such a way that it will compare first the number of 1s and if equal - teh decimal representation of the number.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Check if a value is present in each group Menthix 8 2,587 May-16-2022, 12:25 PM
Last Post: Menthix
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,277 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Anaconda pip install mpyc Error pip-script.py is not present Anldra12 2 7,717 Dec-13-2021, 06:59 PM
Last Post: Anldra12
  How to sort rows based on specific order Mekala 3 2,182 Jul-31-2020, 01:01 AM
Last Post: bowlofred
  No Scripts File present after python installation ag2207 5 4,765 Jul-30-2020, 11:11 AM
Last Post: buran
  How to make this function general to create binary numbers? (many nested for loops) dospina 4 4,331 Jun-24-2020, 04:05 AM
Last Post: deanhystad
  Python function executes twice when region loop is present bluethundr 2 2,595 Jan-07-2020, 03:01 PM
Last Post: bluethundr
  "usr" directory not present and needed for cmd commands? ajetrumpet 2 2,100 Dec-19-2019, 05:59 PM
Last Post: ajetrumpet
  hex file to binary or pcap to binary baran01 1 5,629 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  Deleting files not present in CSV spw2515 1 1,903 Sep-04-2019, 06:06 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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