From 78f896dd625fbbfe33fbd88b55790e55bf0dd57f Mon Sep 17 00:00:00 2001 From: Simon Green Date: Sun, 11 May 2025 11:31:25 +1000 Subject: sgreen solutions to challenge 320 --- challenge-320/sgreen/python/ch-2.py | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100755 challenge-320/sgreen/python/ch-2.py (limited to 'challenge-320/sgreen/python/ch-2.py') diff --git a/challenge-320/sgreen/python/ch-2.py b/challenge-320/sgreen/python/ch-2.py new file mode 100755 index 0000000000..cda60d3d8d --- /dev/null +++ b/challenge-320/sgreen/python/ch-2.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 + +import sys + + +def sum_difference(ints: list) -> int: + """Calculate the absolute difference between digit sum and element + sum of the given list. + + Args: + ints (list): A list of positive integers + + Returns: + int: The absolute difference. + """ + # Check we are only given positive integers + if any(i < 1 for i in ints): + raise ValueError('Only positive integers allowed') + + difference = 0 + for i in ints: + # Single digit integers have no difference + if i > 9: + # Calculate the difference between the number and the sum of the + # individual digits + difference += i - sum(int(d) for d in str(i)) + + return abs(difference) + + +def main(): + # Convert input into integers + array = [int(n) for n in sys.argv[1:]] + result = sum_difference(array) + print(result) + + +if __name__ == '__main__': + main() -- cgit