-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
54 lines (37 loc) · 1.31 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def main():
""" Main function """
nums = []
# Get an integer
i = int(input("Enter a number: "), 10)
# Populate the list
print(f"Enter {i} numbers: ")
for c in range(i):
nums.append(int(input(), 10))
# Sort the list
rearrange(nums, i)
#Print out the list one at a time.
for c in range(i):
print(f"{nums[c]}")
def rearrange(int_list, n):
""" rearrange the list using the number of ones in the binary equivalent of the integers """
c = 0
d = 0
# Loop through the list swapping its element where needed.
for c in range(n-1):
for d in range(n-c-1):
if num_of_ones(int_list[d]) > num_of_ones(int_list[d+1]):
# Swap
int_list[d], int_list[d+1] = int_list[d+1], int_list[d]
elif num_of_ones(int_list[d]) == num_of_ones(int_list[d+1]) and int_list[d] > int_list[d+1]:
# Swap
int_list[d], int_list[d+1] = int_list[d+1], int_list[d]
return int_list
def num_of_ones(n):
""" Calculate the number of ones in the binary equivalent of an integer """
# Convert n into a binary string.
m = format(n, 'b')
# Get the numbers of ones in the binary string.
counter = m.count('1')
return counter
if __name__ == "__main__":
main()