How to make my function more clean and like functional programming pattern

I’m writing a function to calculate the sum of all digit of a number. I’m also learning functional programming pattern but it’s quite hard to me to write both clean and beautiful code.

integer = int(input("Your number: "))


def sum_digits(number: int) -> int:
    result_negative = sum(map(int, tuple(str(number)[2:]))) + int(str(number)[:2])
    return (
        result_negative if str(number)[0] == "-" else sum(map(int, tuple(str(number))))
    )


print(sum_digits(integer))

How do I make this code more functional and clean? Thanks for your help.

In Python you use comprehensions in functional programming:

def sum_digits(number: int) -> int:
    """Sum the digits of the integer number. Ignore any non-digit characters."""
    return sum(
                int(digit)
                for digit in str(number)
                if digit.isdigit())

Note: Now I see that this function sums negative numbers differently from yours which takes the first digit as a negative one. I have never seen such a definition for summing number’s digits. In such a case an alternative approach could be to iterate the number’s characters in pairs … or apply a correction:

def sum_digits(number: int) -> int:
    """Sum the digits of the integer number. Minus sign is part of the first digit."""
    return sum(
                int(digit)
                for digit in str(number)
                if digit.isdigit()
                ) + (2 * int(str(number)[:2]) if number < 0 else 0)
1 Like