0% found this document useful (0 votes)
5 views

Algorithms and data structure

y54yw45yw45
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Algorithms and data structure

y54yw45yw45
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

[email protected].

zw LEROY FRANCISCO ALGORITHMS

Section A: (30 Marks)


Arrupe Jesuit University is automating their student grading system using data structure
elements and Python language. Therefore, the requirement for you, is to answer questions
below to show how this can be achieved and by providing a working system where needed
for a prototype system. The system should be able to accept input of grade of 0 to 100 from
instructor, and give an output result of either failed, First class, pass or distinction).

1. Which Algorithm technique would you use to break down the problem to be more
understandable? Explain the reasons for your choice of algorithm technique to use. [8]
ANSWER:

To break down the problem of creating a student grading system, I would use a Top-Down
Approach in problem-solving, particularly focusing on the divide and conquer technique.
Here’s why this approach is suitable:
1. Simplicity: The creation of output, grading logic, and input processing are some of
the minor parts that make up the grading system. This makes every component easy to
comprehend and use.
2. Modularity: The system becomes modular when the work is broken down into
smaller elements, such as receiving input, classifying the grade, and delivering results.
It is possible to individually create, test, and maintain each module.
3. Scalability: This method makes it simple to incorporate more grading criteria (such
as grading on a curve) without completely redesigning the system in the event that
more are introduced in the future.
4. Clarity: It guarantees that programmers may concentrate on a single facet of the issue
at a time, resulting in more understandable code and improved debugging skills.
5. Effective Problem Solving: Logical flow and decision-making are improved by
approaching and resolving each minor issue separately.
6. Reusability: After the fundamental features for grading logic and input handling are
constructed, they may be used to other areas of the program or to other projects in the
future.

7. Collaboration: By allowing several developers to work on several modules at once,


the development process may be accelerated.

8. Ease of Testing: Before incorporating smaller components into the larger system,
they may be evaluated separately to verify accuracy, which aids in the early detection
of problems.

2. Using the algorithm technique, you selected in question 1, write down the algorithm
example for the grading system indicated above. [7]

ANSWER:
[email protected] LEROY FRANCISCO ALGORITHMS

1.
Start
2. Get Grade Input
o Prompt user to enter a grade (0 to 100).
o Validate the input:
 If valid (numeric and within range), proceed.
 If invalid, show an error message and repeat input prompt.
3. Determine Grade Category
o If grade < 40:
 Set result = "Failed"
o Else If 40 <= grade < 60:
 Set result = "Pass"
o Else If 60 <= grade < 80:
 Set result = "First Class"
o Else:
 Set result = "Distinction"
4. Output Result
o Print the result (grade category).
5. End

Pseudocode Representation
BEGIN

FUNCTION GetGradeInput()
WHILE True
PRINT "Enter the grade (0 to 100): "
INPUT grade
IF grade is numeric AND 0 <= grade <= 100 THEN
RETURN grade
ELSE
PRINT "Invalid input. Please enter a numerical value between 0 and 100."
END WHILE
END FUNCTION

FUNCTION DetermineGradeCategory(grade)
IF grade < 40 THEN
RETURN "Failed"
ELSE IF 40 <= grade < 60 THEN
[email protected] LEROY FRANCISCO ALGORITHMS

RETURN "Pass"
ELSE IF 60 <= grade < 80 THEN
RETURN "First Class"
ELSE
RETURN "Distinction"
END IF
END FUNCTION

FUNCTION Main()
grade = GetGradeInput()
result = DetermineGradeCategory(grade)
PRINT "The result is: " + result
END FUNCTION

Main()
END

Justification:
 The algorithm's beginning and finishing points are indicated by the Begin and End
variables.
 Functions for obtaining input and identifying the grade category make up the
algorithm.
 Because each function has distinct duties, the system as a whole is simpler to
comprehend and manage.
 In order to guarantee that input is legitimate and that the right grading category is
allocated in accordance with the grade provided, control structures like loops and
conditionals are used.
This methodical technique, which is consistent with the top-down approach employed in
programming, clarifies the input flow and grading rationale.

3. Write a PYTHON program to accept five students with student id, student name and
total from two assignments marks scored in python programming and print the result.
i. If marks are below 49. Print “You failed”.
ii. If the marks a above 50 and below 59, Print “Congratulation, you Passed”
iii. If the marks are above 60 and below 74, Print “Congratulation, you got First Class”
[email protected] LEROY FRANCISCO ALGORITHMS

iv. If the marks are above 75, Print “Congratulation, you got Distinction”
v. If the marks are above 101, print “invalid”
vi. Display Grades: Implement a function to display all student grades in sorted order
based on student ID.
vii. Arrange and sort marks in sorting algorithms of your choice for the five students
[15]
ANSWERS:
CODE:
class Student:
def __init__(self, student_id, name, marks):
self.student_id = student_id
self.name = name
self.marks = marks

def determine_grade(self):
if self.marks < 0 or self.marks > 100:
return "Invalid"
elif self.marks < 50:
return "You failed."
elif 50 <= self.marks < 60:
return "Congratulations, you Passed."
elif 60 <= self.marks < 74:
return "Congratulations, you got First Class."
elif self.marks >= 75:
return "Congratulations, you got Distinction."
def input_students():
students = []
for i in range(5):
student_id = input(f"Enter Student ID for student {i + 1}: ")
name = input(f"Enter Student Name for student {i + 1}: ")
[email protected] LEROY FRANCISCO ALGORITHMS

assignment1 = float(input(f"Enter marks for Assignment 1 for {name}: "))


assignment2 = float(input(f"Enter marks for Assignment 2 for {name}: "))
total_marks = (assignment1 + assignment2) / 2 # Average of two assignments
students.append(Student(student_id, name, total_marks))
return students

def display_grades(students):
print("\nStudent Grades:")
for student in sorted(students, key=lambda x: x.student_id):
grade_message = student.determine_grade()
print(f"ID: {student.student_id}, Name: {student.name}, Marks: {student.marks:.2f} -
{grade_message}")

def main():
students = input_students()
display_grades(students)

if __name__ == "__main__":
main()
[email protected] LEROY FRANCISCO ALGORITHMS

IMPLEMENTATION ON IDE:
[email protected] LEROY FRANCISCO ALGORITHMS

Section B (70 Marks)


The menu should include the following options:
a) apply for a loan – to allow users to capture loan application details as described
in the scenario. This entails inserting a new node to a singly linked list that
processes entries on the order of arrival.
b) update status – used to update the status of a particular application. Status can
be one of the following: pending, approved, deleted, where pending is the default
status for all new applications.
c) Delete application – used to allow users to delete a particular application. Users should
enter the applicant’s email address to retrieve the application to be deleted.
d) Display applications – this should display all the applications in the system,
showing all details of the application, including its status. If there are no
applications yet, display an appropriate message to a user.
e) Lookup a record – used to search a particular application based on a user-entered
search key. If a record exists, display the address of its node and the next node.
f) Display accepted applications – displays only applications whose status is “accepted”.
g) Display deleted applications – displays only applications that were deleted. Display
an appropriate message if there are no deleted applications.
h) Recover applications – restores one application at a time, based starting with the
one deleted last (LIFO). All recovered applications should be considered as new
applications that have just been initiated.
i) Store deleted application – stores deleted applications in an appropriate data structure.
j) Your program should continue running, giving users an option to continue until
they choose to exit.

ANSWERS:
CODE:
class LoanApplication:
def __init__(self, first_name, surname, email, amount):
self.first_name = first_name
self.surname = surname
self.email = email
[email protected] LEROY FRANCISCO ALGORITHMS

self.amount = amount
self.status = 'pending'
self.next_application = None # Pointer for singly linked list

def __repr__(self):
return f"{self.first_name} {self.surname} - {self.amount} ({self.status})"

class LoanApplicationSystem:
def __init__(self):
self.head = None # Head of the linked list
self.deleted_applications = []

def apply_loan(self, first_name, surname, email, amount):


application = LoanApplication(first_name, surname, email, amount)
if not self.head:
self.head = application
else:
current = self.head
while current.next_application:
current = current.next_application
current.next_application = application

def update_status(self, email, new_status):


if new_status not in ['pending', 'approved', 'deleted']:
print("Invalid status. Status can only be 'pending', 'approved', or 'deleted'.")
return

current = self.head
prev = None
while current:
if current.email == email:
if new_status == 'deleted':
self.deleted_applications.append(current)
if current == self.head: # If the head is being deleted
self.head = current.next_application
else:
prev.next_application = current.next_application
else:
current.status = new_status
return
prev = current
current = current.next_application
print("Application not found.")

def delete_application(self, email):


[email protected] LEROY FRANCISCO ALGORITHMS

self.update_status(email, 'deleted')

def display_applications(self):
if not self.head:
print("No applications found.")
return
current = self.head
while current:
print(current)
current = current.next_application

def lookup_record(self, email):


current = self.head
while current:
if current.email == email:
print(f"Application found: {current}")
print(f"Address of this node: {id(current)}")
print(f"Next node address: {id(current.next_application) if current.next_application
else None}")
return
current = current.next_application
print("Record not found.")

def display_accepted_applications(self):
current = self.head
has_accepted = False
while current:
if current.status == 'approved':
print(current)
has_accepted = True
current = current.next_application
if not has_accepted:
print("No accepted applications.")

def display_deleted_applications(self):
if not self.deleted_applications:
print("No deleted applications.")
return
print("Deleted Applications:")
for app in self.deleted_applications:
print(app)

def recover_application(self):
if not self.deleted_applications:
print("No applications to recover.")
return
[email protected] LEROY FRANCISCO ALGORITHMS

recovered_application = self.deleted_applications.pop() # Restore last deleted


application
recovered_application.status = 'pending'
self.apply_loan(recovered_application.first_name, recovered_application.surname,
recovered_application.email, recovered_application.amount)

def main():
loan_system = LoanApplicationSystem()

while True:
print("\nMenu:")
print("a) Apply for a loan")
print("b) Update status")
print("c) Delete application")
print("d) Display applications")
print("e) Lookup a record")
print("f) Display accepted applications")
print("g) Display deleted applications")
print("h) Recover last deleted application")
print("i) Exit")

choice = input("Choose an option: ").strip().lower()

if choice == 'a':
first_name = input("Enter first name: ")
surname = input("Enter surname: ")
email = input("Enter email: ")
amount = float(input("Enter amount applied for: "))
loan_system.apply_loan(first_name, surname, email, amount)

elif choice == 'b':


email = input("Enter email of application to update: ")
new_status = input("Enter new status (pending/approved/deleted): ")
loan_system.update_status(email, new_status)

elif choice == 'c':


email = input("Enter email of application to delete: ")
loan_system.delete_application(email)

elif choice == 'd':


print("Current Applications:")
loan_system.display_applications()

elif choice == 'e':


email = input("Enter email of application to lookup: ")
loan_system.lookup_record(email)
[email protected] LEROY FRANCISCO ALGORITHMS

elif choice == 'f':


print("Accepted Applications:")
loan_system.display_accepted_applications()

elif choice == 'g':


loan_system.display_deleted_applications()

elif choice == 'h':


loan_system.recover_application()

elif choice == 'i':


print("Exiting...")
break

else:
print("Invalid choice. Please choose again.")

if __name__ == "__main__":
main()

IMPLEMENTATION ON IDE:
A) Apply for a loan:

b) Update status:
[email protected] LEROY FRANCISCO ALGORITHMS

c) Delete application:

d) Display applications:
[email protected] LEROY FRANCISCO ALGORITHMS

e) Lookup a record:

f) Display accepted applications


[email protected] LEROY FRANCISCO ALGORITHMS

g) Display deleted applications:

h) Recover last deleted application:

i) Exit The System:


[email protected] LEROY FRANCISCO ALGORITHMS

You might also like