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.
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)