HUNTER FRASER
HUNTER FRASER

Reputation: 61

How to write a function that filters numbers if they lie within a range

I want to write a function inRange, that should return a list containing all, and only, the elements of l whose values are between low and high inclusive. For example, inRange(3, 10, [2, 3, 7, 17, 10, 7, -9]) returns [3, 7, 10, 7]. I can only do this function using map, filter, reduce, list, lambda.

This is my current code which does not work:

def inRange(lo, hi, l):
    return list(filter(lambda lo, hi, l: l in range(lo, hi))

print(inRange(10, 20, [10, 14, 16, 17, 20, 21, 23, 12]))

Upvotes: 0

Views: 481

Answers (1)

Animikh Aich
Animikh Aich

Reputation: 647

You are looking for this function:

def inRange(lo, hi, l):
     return list(filter(lambda i: lo <= i <= hi, l))

print(inRange(10, 20, [10, 14, 16, 17, 20, 21, 23, 12]))

Output:

[10, 14, 16, 17, 20, 12]

Reference:

Upvotes: 1

Related Questions