Need Help: Sort of Binary numbers based on 1's present - 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: Need Help: Sort of Binary numbers based on 1's present (/thread-4134.html) |
Need Help: Sort of Binary numbers based on 1's present - abinashj - Jul-25-2017 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 . RE: Need Help: Sort of Binary numbers based on 1's present - buran - Jul-25-2017 what have you tried so far and what problem(s) you are not able to resolve? RE: Need Help: Sort of Binary numbers based on 1's present - abinashj - Jul-25-2017 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 . RE: Need Help: Sort of Binary numbers based on 1's present - buran - Jul-25-2017 Did you read my link? We need to see your code RE: Need Help: Sort of Binary numbers based on 1's present - abinashj - Jul-25-2017 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 RE: Need Help: Sort of Binary numbers based on 1's present - buran - Jul-25-2017 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. |