Python Project: Filter Numbers with a List
Python: Bite 107
Filter numbers with a list comprehension
I was happy to join Pybites and start to solve the code-challenges, my problem from the first bite was that i am solving the challenges in other online python interpreter, and it looks working fine and the output seams as it should be, but once I copy the code in Pybite portal and doing the code test it fail and gives errors.
In this challenge Bite 107, after a list of numbers the task is to return the positive even number. Now in the task description it mentioned to use (elegant list comprehension; one line of code). I start to work on it, immediately it jump to my head a for loop and if each item is even and more than 0 add it to my_list, then return my_list. After coding, the output was a list with positive and even numbers in a Number-list, but it failed in the Bite test portal. WAY!.
This type of failure was against me in other challenges also, and i was just setting all the day thinking what happen!. With Bite 107 I decide to click on “Show Solution” button just to see what is wrong.
One line code:The Solution was in one line of list brackets after a return statement congaing for and if without my_list. just like that. I start smiling, and ask my self “How could i know that i can write it like this??”. Yes it is beautiful, Yes elegant and yes one line of code, and yes my-way of coding gives the answer that we want, my code pass my testing exam.
Concloguen: I think i come up with a good resource of learning python, I don’t want to read book’s but reading codes that doing things and having the alternatives of writing same code; this will help me a lot. I am not coding for NASA or in other sensitive area that processing time is essential and micro-milli seconds make difference, so one line of four-line to-me is OK. 🙂
Acknowledge: I’d like to thank Pybite community for there contribution in spreading knowledge and codes, and for this challenges. I will read the challenges, and try my best to solve them as elegant as i can, also i will not stop in one point because my code is 2 lines more than what should be.
Last thing, Bite 107 here is my code and the elegant code. Be calm and positive.
The Code:
#First: My Code
def filter_positive_even_numbers(numbers):
my_list=[]
for i in range(len(numbers)):
if (i>0 and i%2==0) :my_list.append(i)
return my_list
print (filter_positive_even_numbers(numbers))
#The optimal solution
def filter_positive_even_numbers(numbers):
return[n for n in numbers if n > 0 and n % 2 == 0]