0

I am a beginner of python, thank you so much!

function:

def count(c):
    return c.count(1)

count(1,1,1,11,1,12,1)

This function doesn't work, I want to create a function count how many 1’s?

lambda:

counts = lambda m:count('m') 
counts('what is you name, my name is mammy!')

This lambda doesn't work, too. I want to create a lambda count how many 'm''s?

2 Answers 2

2

Just add a * in front of c to make it take all the leftover arguments and sets it to a list

def count(*c):
    return c.count(1)

count(1,1,1,11,1,12,1)

and the lambda function can be:

counts = lambda m: m.count('m') 
counts('what is you name, my name is mammy!')
Sign up to request clarification or add additional context in comments.

Comments

1

Your first example fails because you're passing multiple arguments, and it only accepts one (presumably a list). One way to fix it would be to pass a list:

def count(c):
    return c.count(1)

print(count([1,1,1,11,1,12,1]))  # 5

Another way to fix it is to allow multiple parameters but treat them as a list. Here's how you can do that:

def count(*c):
    return c.count(1)

print(count(1,1,1,11,1,12,1))  # 5

Your second example is missing a thing to call count on. Again, one possible fix:

counts = lambda x: x.count('m')
print(counts('what is you name, my name is mammy!'))  # 6

1 Comment

Thank you so much!

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.