Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lambda functions to sum digits and count digits

How can I convert these two functions to use lambda notation?

def sum_digits(number):
    if number == 0:
        return 0
    else:
        return (number % 10) + sum_digits(number / 10)

def count_digit(number):
    if number == 0:
        return 0
    else:
        return 1 + count_digit(number/10)
like image 531
Belovedad Avatar asked Jun 11 '26 07:06

Belovedad


1 Answers

sum_digits = lambda number: 0 if number == 0 else (number % 10) + sum_digits (number / 10)

count_digit = lambda number: 0 if number == 0 else 1 + count_digit(number/10)

Incidentally, this is a bad time to use lambdas, since you need the function names in order for them to call themselves. The point of lambdas is that they're anonymous.

like image 166
Arya McCarthy Avatar answered Jun 12 '26 20:06

Arya McCarthy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!