2

Write a Python lambda function which takes a list called my_list and returns a list which includes only even numbers in the same order.

My solution:

f = list(filter(lambda x: (x % 2 == 0), my_list))
print(f)

I'm having issues because I'm doing a homework problem online and it runs various test cases on it and it says my_list isn't defined. Which I understand why that is, because it isn't... but it seems like the question is looking for a broad function which I don't know how to do in this case.

2 questions:

  1. Does my solution look correct?
  2. If so, how do I tailor this so that the homework will accept various inputs?
2
  • You can just assign to my_list a list of arbitrary integers as test data, e.g. my_list = [3, 7, 4, 1, 2] Commented Apr 3, 2020 at 17:34
  • 1
    From the first line of your post, maybe you are looking for something like this? f = lambda lst: [x for x in lst if x % 2 == 0] You can call it on any list of integers. Commented Apr 3, 2020 at 17:39

2 Answers 2

1

It does not look correct since f is not a lambda function but a list. OK, it uses lambda but it is not lambda.

You would probably need to write something like:

f = lambda my_list: list(filter(lambda x: (x % 2 == 0), my_list))

or similar.

For example:

f = lambda my_list: [x for x in my_list if x % 2 == 0]

should also satisfy the requirement.


Of course now print(f) will "print the function".

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

Comments

1

I'm doing a homework problem online and it runs various test cases

Your function is actually correct. But, well, online coding assessment usually use a stdin as input. Python use input() method to retrieve string from stdin. So if you want your submission accept various input, you probably need to add this.

my_list = list(map(int, input().split(' ')))

That will split string input by space character ' ' to be a list. Then, all content in list converted to integer by map function. Since the return value of map function is not a list, you need list method to convert map result into list. The new list will be saved to my_list variable.

But, again, it depends on your input specification. If your input specification are eg: "1, 2, 4, 5". use ', ' as split parameter.

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.