Algorithms and data structure
Algorithms and data structure
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.
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
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
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 = []
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.")
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 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
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")
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)
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: