2

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

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

5 Comments

i thought i was wrong if i did that but it's just someone asking for this alternative method since i converted those two functions into an HOF already
Do you mean that you want a non-recursive form of each function?
No, I purposely wrote them recursively. I just wanted to know how i could replace the function itself by using a lambda notation instead. My HOF does this: digits(number,term). Now I can replace term with the lambda function.
A perk of Python is that you don't even need to write them as lambdas to do that. Pass in the function as an argument. If I'm understanding your intent, you can call digits(number, sum_digits) even when it's not a lambda.
I know, but I have never been good with lambda because I don't see the use of it most of the time. It was specifically required as an comment in my overall program.
5

A string-oriented approach wouldn't require recursion:

sum_of_digits = lambda n: sum(int(d) for d in str(n))
count_digit = lambda n: len(str(n))

Comments

4

Use a conditional expression for the body of the lambda:

>>> sum_digits = lambda n: 0 if n == 0 else (n % 10) + sum_digits(n // 10)
>>> count_digit = lambda n: 0 if n == 0 else 1 + count_digit(n // 10)

Also, if is preferred to use // for the division so that the code will still work in Python 3.

Comments

0
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)
print(sum_digits(2546))
print(count_digit(2546))

Will work on python 3 too...

Comments

0
print(list(map(lambda x: sum(int(i) for i in str(x)),list(map(int,input().split())))))

this might be useful for reading and using lamda function on the same line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.