14/18: quick question


#1
print filter(lambda x: range(30,71), squares)

Why doesn't this work? Why do you have to put

print filter(lambda x: x>=30 and x<=70, squares)

Thanks!!! :smiley:


#2

the range() function creates a list(in python 2) but the goal for this exercise is not to to create a list but rather to extract elements from a given list .Test the code below to see the difference

import random
#just generating a list of length 50
#with random numbers between 0 and 50
nums = random.sample(range(50),50)

#the first filter method
ans1 = filter(lambda x: range(30,71), nums)

#the second filter method
ans2 = filter(lambda x: 30 < x < 71 , nums )

print "filter(lambda x:range(30,71), nums) gives:\n", ans1
print "filter(lambda x: 30 < x < 71, nums) gives:\n",ans2

#are they the same
print sorted(ans1) == sorted(ans2) #False

You can directly TEST IT HERE


#3

Hi @laurlaurbear ,

It is OK to use the range function as part of the test here, but to solve this problem, we need to test how the value of x relates to the specified range. We can do this ...

print filter(lambda x: x in range(30, 71), squares)

For a much larger interval, this might not be the most efficient way of solving the problem, because in that case the range function would need to create a very large list, just to perform a test.


#5

print filter(lambda x:30<=x<=70,squares)
its work impeccably..:smiley: