Program to filter all values which are greater than x in an array

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums. We also have another number x. We have to find all numbers from nums which are less than x by filtering. In we use python there is one filter() method that takes function as argument and filter using this function.

So, if the input is like nums = [1,5,8,3,6,9,12,77,55,36,2,5,6,12,87] x = 50, then the output will be [1, 5, 8, 3, 6, 9, 12, 36, 2, 5, 6, 12]

To solve this, we will follow these steps −

  • define a function f, this will take an argument a

  • if a < x, then return true, otherwise false

  • left_items := filter nums using the function f

  • convert filter object left_items to list and return

Example

Let us see the following implementation to get better understanding

def solve(nums, x):
   left_items = filter(lambda a: a < x, nums)
   return list(left_items)

nums = [1,5,8,3,6,9,12,77,55,36,2,5,6,12,87]
x = 50
print(solve(nums, x))

Input

[1,5,8,3,6,9,12,77,55,36,2,5,6,12,87], 50

Output

[1, 5, 8, 3, 6, 9, 12, 36, 2, 5, 6, 12]
raja
Published on 12-Oct-2021 09:38:55

Advertisements