Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python exercise
#1
For the file attached below, add the following two functions to the code.

1. A search by programme ID function. When this function is selected, a user can use the programme ID as the searching keyword to search all the students who have that programme ID. If found, the student's IDs and names will be displayed, otherwise, no found should be reported.

2. A history of search function. When this function is selected, a user can display previous searching results of "searching by student ID" function, up to the five searches. The display should contain the student IDs and student names. If there are no five previous searches, the function should inform the user.


I am new in Python and need some tips to do this exercise, hope that someone can help!!

File: students.py

from listm import *
from studentm import *

students = List()

choice = menu() 
while (choice!=0):
    if (choice == 1):
        print("This function will return the size of the list")
        listlen = length(students)
        print(f"The size of the student list is {listlen}.")
        print("Press enter to continue.")
        input('')
    elif (choice == 2):
        print("This function appends a new record on the end of the list")
        student = inputstinfo()
        insert(students, length(students)+1, student)
        print("The appending function is done.")
        print("Press enter to continue.")
        input('')
    elif (choice == 3):
        print("This function insert a new record in the corresponding position")
        print("Please input the position:", end='')
        position = int(input())
        student = inputstinfo()
        insert(students, position, student)
        print("The insertion function is done.")
        print("Press enter to continue.")
        input('')
    elif (choice == 4):
        print("This function delete a record in the specified position")
        print("Please input the position:", end='')
        position = int(input())
        delete(students, position)
        print("The deletion function is done.")
        print("Press enter to continue.")
        input('')
    elif (choice == 5):
        print("This funtion locate a record based on student ID")
        print("Please input the student id:", end='')
        sid = input()
        position = locatebyid(students, sid)
        if position < 0:
            print(f"Student with sid={sid} does not exist.")
        else:
            print(f"Student with sid={sid} is at position {position}")
        print("The locate function is done.")
        print("Press enter to continue.")
        input('')
    elif (choice == 6):
        print("This function display the record in specified position")
        print("Please input the position:", end='')
        position = int(input())
        student = get(students, position)
        if student != -1:
            displaystinfo(student)
        else:
            print(f"There is no student at position {position}")
        print("The get function is done.")
        print("Press enter to continue.")
        input('')
    elif (choice == 7):
        print("This function diplay all the record in the list")
        for student in students.lst:
            displaystinfo(student)
        print("The display function is done.")
        print("Press enter to continue.")
        input('')
    elif (choice == 8):
        print("This is the search by programme function")
        print("Please input the programme ID:", end ='')
        pid = String(input())
        student = get(students, pid)
        if student != -1:
            searchProgram(student)
        else:
            print(f"There is no student studying at this programme")
        print("Press enter to continue.")
        input('')
    elif (choice == 9):
        print("This is the history search function")
        print("Under construction.")
        print("Press enter to continue.")
        input('')
    elif (choice == 10):
        print("This is my own function")
    elif (choice == 0):
        print("Now quit, thank you!")
    choice = menu()
File: studentm.py

class Student:
    def __init__(self, sid=None, name=None, gender=None, pid=None):
        if sid is None:
            self.id = ""
        else: self.id = sid
        if name is None:
                self.name = ""
        else:
            self.name = name
        if gender is None:
                self.gender = ""
        else:
            self.gender = gender
        if pid is None:
                self.pid = ""
        else:
            self.pid = pid

def menu():
	print("\n")
	print("\n")
	print("\n")
	print("	Please type 1-8 for student record action")
	print("	1 - Return the size of the list")
	print("	2 - Append a new record at the end")
	print("	3 - Insert a new record at position i")
	print("	4 - Delete the record at position i")
	print("	5 - Locate a record based on student ID")
	print("	6 - Display the record at position i")
	print("	7 - Display all the records")
	print("	8 - Search by programme")
	print("	9 - Search history")
	print("	0 - Quit")
	print("\n")
	print("	Your choice: ", end='')
	choice=int(input())
	print("\n")
	print("\n")
	print("\n")
	return choice

def inputstinfo():
        sid = input("Please input the student's id: ")
        name = input("Please input the student's name: ")
        gender = input("Please input the student's gender: ")    
        pid = input("Please input the student's program id: ")
        tmps = Student(sid, name, gender, pid)
        return tmps;

def displaystinfo(student):
        print(f"The student's info are: {student.id}, {student.name}, {student.gender}, {student.pid}.")

def searchProgram(student):
    print(f"The student who participanted in this programme is: {student.id}, {student.name}.")


File: listm.py

class List:
    def __init__(self, lst=None):
        if lst is None:
                    self.lst = []
        else:
            self.lst = lst


def length(l):
    return len(l.lst)


def isempty(l):
    if len(l.lst)==0:
        return True
    else:
        return False

def get(l, i):
    if isempty(l):
        print("The get() is unsuccessful!")
        print("The list is empty!")
        return -1
    elif (i<1) or (i>length(l)):
        print("The get() is unsuccessful!")
        print("The index given is out of range!")
        return -1
    else:
        return(l.lst[i-1])

def locatebyvalue(l, x):
    position = 1
    for item in l.lst:
        if x == item:
            return position
        else:
            position = position+1
    return -1        

def locatebyid(l, idd):
    position = 1
    for item in l.lst:
        if item.id == idd:
            return position
        else:
            position = position+1
    return -1        

def insert(l, i, x):
    if (i<1) or (i>length(l)+1):
        print("The insert() is unsuccessful!")
        print("The index given is out of range!")
        
    else: 
        l.lst.insert(i-1, x)

def delete(l, i):
    if isempty(l):
        print("The delete() is unsuccessful!")
        print("The list is empty!")
        return
    elif (i<1) or (i>length(l)):
        print("The delete() is unsuccessful!")
        print("The index given is out of range!")
        return
    else: 
        del l.lst[i-1]


def display(l):
    print(l.lst)
Reply
#2
Look at the search by student id. To search by programme id, you just need to redo that code, but searching by pid instead of id. The difference is that instead of returning the first position found, you want to append each student that matches to a list (you start out with an empty list before looping through the students).

For the search history, add a history list to the main program. Every time you do a search, append the results to the list. When they want to see the history, show them the last 5 items (history[-5:]).

If you were given this code by your teacher to modify, then your teacher has no clue how to program Python. That is really bad code. They added complication for no reason. Why rewrite all of the list methods into functions, instead of just using the list methods? That isempty function is especially bad. And why have a class with all the defaults set to None, and a bunch of code to change all the Nones to empty strings? Why not just make the defaults empty strings? This really smells like someone who programs in another language who is trying to teach you that other language using Python.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Many thanks for your help!!
Yes, the code is very confusing, can't understand it especially for the "listm.py" file
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Exercise Vasanth0910 1 1,860 May-15-2020, 04:41 PM
Last Post: pyzyx3qwerty
  Python exercise janaraguz 2 2,516 Sep-22-2018, 08:43 PM
Last Post: ichabod801
  Simple exercise - how to write in python tomtom55 6 4,915 Sep-28-2017, 07:18 PM
Last Post: nilamo
  Python Exercise: Generate a two-dimensional array smbx33 4 10,686 Apr-22-2017, 11:51 PM
Last Post: smbx33

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020