Reputation: 1152
I was wondering if someone can help me with a homework problem.
Write a function, func(a,x), that takes an array, a, x being both numbers, and returns an array containing only the values of a that are greater than or equal to x
I have
def threshold(a,x):
for i in a:
if i>x: print i
But this is the wrong method as I'm not returning it as an array. Can someone hint me the right direction. Thanks a lot in advance
Upvotes: 0
Views: 317
Reputation: 8123
I think the homework problem is to actually implement a filter function. Not just use the built in one.
def custom_filter(a,x):
result = []
for i in a:
if i >= x:
result.append(i)
return result
Upvotes: 0
Reputation: 2981
def threshold(a,x):
vals = []
for i in a:
if i >= x: vals.append(i)
return vals
Upvotes: 2
Reputation: 880917
You could use a list comprehension:
def threshold(a, x):
return [i for i in a if i > x]
Upvotes: 4
Reputation: 251176
use the in-built function filter()
:
In [59]: lis=[1,2,3,4,5,6,7]
In [61]: filter(lambda x:x>=3,lis) #return only those values which are >=3
Out[61]: [3, 4, 5, 6, 7]
Upvotes: 6