From 9570cd789d0f24fcfba65675b371c5feae0e3dc8 Mon Sep 17 00:00:00 2001 From: Simon Green Date: Sun, 2 Jun 2024 16:44:05 +1000 Subject: sgreen solutions to challenge 271 --- challenge-271/sgreen/python/ch-2.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100755 challenge-271/sgreen/python/ch-2.py (limited to 'challenge-271/sgreen/python/ch-2.py') 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() -- cgit