aboutsummaryrefslogtreecommitdiff
path: root/challenge-271/sgreen/python/ch-2.py
diff options
context:
space:
mode:
Diffstat (limited to 'challenge-271/sgreen/python/ch-2.py')
-rwxr-xr-xchallenge-271/sgreen/python/ch-2.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/challenge-271/sgreen/python/ch-2.py b/challenge-271/sgreen/python/ch-2.py
new file mode 100755
index 0000000000..7ebb7f412a
--- /dev/null
+++ b/challenge-271/sgreen/python/ch-2.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+
+import sys
+
+
+def sort_by_1_bits(ints: list) -> list:
+ """
+ Sorts a list of integers based on the number of set bits (1s) in their
+ binary representation. If they are equal, they are sorted by their value.
+
+ Args:
+ ints (list): A list of integers to be sorted.
+
+ Returns:
+ list: A new list of integers sorted based on the criteria above.
+ """
+ sorted_ints = sorted(ints, key=lambda x: (bin(x).count('1'), x))
+ return sorted_ints
+
+
+def main():
+ # Convert input into integers
+ array = [int(n) for n in sys.argv[1:]]
+ result = sort_by_1_bits(array)
+ print(tuple(result))
+
+
+if __name__ == '__main__':
+ main()