Python program to search objects from an array of objects using filter() method

Here, we will see a program to search objects from an array of objects using the filter() method in Python.
Submitted by Shivang Yadav, on February 18, 2021

Problem Statement: Program to search objects from array of objects using the filter() method.

Problem Description: In this program, we will create an array of objects and then search for objects with marks in a certain range using the filter() method.

Class Used in the program:

  • Class : student
    • Method : getStudentInfo() : gets input of the student information from the user.
    • Method : putStudentInfo() : print in student information to the screen.
    • Method : searchMarks() : returns boolean value if the marks are in the given range.

Algorithm:

  • Step 1: Taking input from the user for id, name, marks of the student.
  • Step 2: We will return the details of all students who passed the exam with 1st division i.e. that marks more that 60. For this we will use the inbuilt filter() method and pass the searchMarks() method with range from 60 to 100. And this give us an array of objects of all students that satisfy the condition.
  • Step 3: Print the information of all students passed with 1st division.

Program to search objects from an array of objects using filter method

class Student:
    def getStudentInfo(self):
        self.__rollno=input("Enter Roll Number : ")
        self.__name = input("Enter Name : ")
        self.__marks = int(input("Enter Marks : "))
        
    def printInfo(self):
        print("Roll No. : ", self.__rollno,", Name : ", self.__name, ", Marks : " , self.__marks)
        
    def SearchMarks(self,subject,min,max):
        if(subject=='marks' and (self.__marks >=min and self.__marks<=max)):
            return True
        else:
            return False

SL=[]
while(True):
    S=Student()
    S.getStudentInfo()
    SL.append(S)
    ch=input("Add More y/n?")
    if(ch=='n'):break

print("All students whose passed the exam are ")
RL=list(filter(lambda S : S.SearchMarks('marks',60,100),SL))
for S in RL:
  S.printInfo()

Output:

Enter Roll Number : 3
Enter Name : John
Enter Marks : 87
Add More y/n?y
Enter Roll Number : 5
Enter Name : Jane
Enter Marks : 654   45
Add More y/n?y
Enter Roll Number : 1
Enter Name : Nupur
Enter Marks : 99
Add More y/n?n
All students whose passed the exam are 
Roll No. :  3 , Name :  John , Marks :  87
Roll No. :  1 , Name :  Nupur , Marks :  99

Python class & object programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.