0% found this document useful (0 votes)
17 views14 pages

Problem Set

The document outlines a problem set for an Algorithms II course, focusing on employee, student, and complex number management using Python. It includes detailed specifications for creating programs to manage employee and student records, as well as operations on complex numbers, with functions for input, display, save/load, search, update, and delete. Each exercise provides a structured approach to defining data, implementing algorithms, and includes Python code examples for clarity.

Uploaded by

far4vac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views14 pages

Problem Set

The document outlines a problem set for an Algorithms II course, focusing on employee, student, and complex number management using Python. It includes detailed specifications for creating programs to manage employee and student records, as well as operations on complex numbers, with functions for input, display, save/load, search, update, and delete. Each exercise provides a structured approach to defining data, implementing algorithms, and includes Python code examples for clarity.

Uploaded by

far4vac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Algorithms II Problem Set I

UNIVERSITY IBN TOFAIL


Algorithms II

Problem Set III

Exercise 1: Employee Management


We want to create a Python program to manage a list of employees. Each employee is
modeled as a dictionary containing the following fields:

• id: integer (unique identifier of the employee)

• name: string

• age: integer

• position: string

All employees will be stored in a list of dictionaries. The data can also be saved and
loaded from a text file named "[Link]", where each line represents an employee,
with fields separated by commas.
Required work:

1. Define the structure of an employee using a dictionary.

2. Write a function input_employee() that returns a dictionary representing an em-


ployee entered by the user.

3. Write a function display_employee(employee) that displays the information of a


given employee.

4. Write the main program that:

• Asks the user to enter information for n employees (n ≤ 10).


• Stores these employees in a list.
• Displays the names of employees whose age is strictly greater than 30 years.

5. Write a function save_employees(list, filename) that saves the list of employees


to a text file ("[Link]"), with each employee on a line in the format: id, name,
age, position.

6. Write a function load_employees(filename) that reads data from the text file and
returns the list of employees (as dictionaries).

7. Write a function search_employee(list, id) that searches for an employee by id


in the list and displays their information if they exist.

1
Algorithms II Problem Set I

8. Write a function update_position(list, id, new_position) that updates the


position of an employee identified by their id.

9. Write a function delete_employee(list, id) that removes the employee with the
given id from the list, then updates the "[Link]" file.

10. Write a function sort_employees_by_age(list) that sorts the list of employees


by ascending age and displays the sorted list.

2
Algorithms II Problem Set I

Correction
Algorithm
Require: Operations for employee management (add, display, save, load, search,
update, delete, sort)
Ensure: Manage employee data
Define employee dictionary with fields: id, name, age, position
Define function input_employee():
Read id, name, age, position from input
return employee dictionary
Define function display_employee(employee):
print employee details
Define function save_employees(list, f ilename):
for each employee in list do
employee data to file in CSV format
end for
Define function load_employees(f ilename): file line by line CSV into employee
dictionaries
return list of employees
Define function search_employee(list, id):
for each employee in list do
if [Link] == id then
return employee
end if
end for
return None
Define function update_position(list, id, new_position):
for each employee in list do
if [Link] == id then
[Link] = new_position
end if
end for
Define function delete_employee(list, id): employee with matching id from list
Define function sort_employees_by_age(list): list by [Link] in ascending
order

Python Implementation

3
Algorithms II Problem Set I

Correction

1 def input_employee () :
2 return {
3 ’ id ’: int ( input ( " Enter ID : " ) ) ,
4 ’ name ’: input ( " Enter name : " ) ,
5 ’ age ’: int ( input ( " Enter age : " ) ) ,
6 ’ position ’: input ( " Enter position : " )
7 }
8
9 def display_employee ( emp ) :
10 print ( f " ID : { emp [ ’ id ’]} , Name : { emp [ ’ name ’]} , Age : { emp [ ’ age
’]} , Position : { emp [ ’ position ’]} " )
11
12 def save_employees ( employees , filename ) :
13 with open ( filename , ’w ’) as f :
14 for emp in employees :
15 f . write ( f " { emp [ ’ id ’]} ,{ emp [ ’ name ’]} ,{ emp [ ’ age ’]} ,{ emp [ ’
position ’]}\ n " )
16
17 def load_employees ( filename ) :
18 employees = []
19 with open ( filename , ’r ’) as f :
20 for line in f :
21 parts = line . strip () . split ( ’ , ’)
22 employees . append ({
23 ’ id ’: int ( parts [0]) ,
24 ’ name ’: parts [1] ,
25 ’ age ’: int ( parts [2]) ,
26 ’ position ’: parts [3]
27 })
28 return employees
29
30 def search_employee ( employees , emp_id ) :
31 for emp in employees :
32 if emp [ ’ id ’] == emp_id :
33 return emp
34 return None
35
36 def update_position ( employees , emp_id , new_pos ) :
37 for emp in employees :
38 if emp [ ’ id ’] == emp_id :
39 emp [ ’ position ’] = new_pos
40
41 def delete_employee ( employees , emp_id ) :
42 return [ emp for emp in employees if emp [ ’ id ’] != emp_id ]
43
44 def s o r t_ em p l oy ee s_ by _a ge ( employees ) :
45 return sorted ( employees , key = lambda x : x [ ’ age ’ ])

4
Algorithms II Problem Set I

Correction

1 # Main program
2 n = int ( input ( " Enter number of employees ( n 10) : " ) )
3 employees = [ input_employee () for _ in range ( n ) ]
4 print ( " \ nEmployees over 30: " )
5 for emp in employees :
6 if emp [ ’ age ’] > 30:
7 display_employee ( emp )
8 save_employees ( employees , " employees . txt " )
9 loaded = load_employees ( " employees . txt " )
10 search_id = int ( input ( " Enter ID to search : " ) )
11 found = search_employee ( loaded , search_id )
12 if found :
13 display_employee ( found )
14 update_position ( loaded , search_id , " Manager " )
15 loaded = delete_employee ( loaded , search_id )
16 sorted_employees = s o rt _e m p l o y e e s _ b y _ a g e ( loaded )
17 print ( " \ nSorted Employees : " )
18 for emp in sorted_employees :
19 display_employee ( emp )
Listing 1: Python Code for Exercise 1

5
Algorithms II Problem Set I

Exercise 2: Student Management


We want to develop a Python application to manage a list of students. Each student is
represented by a dictionary with the following fields:

• code: integer (unique identifier of the student)

• last_name: string

• first_name: string

• gender: character (’M’ for male or ’F’ for female)

• average: float (average grade out of 20)

Students are stored in a list of dictionaries and can be saved or loaded from a JSON
file named "[Link]".
Required work:

1. Declare the Student record using a dictionary.

2. Write a function input_student() that allows filling in the fields of a student


entered by the user, and returns a dictionary.

3. Write a function display_student(student) that displays the information of a


given student.

4. Write a main program that:

• Asks the user to enter information for n students (with n ≤ 100), and stores
them in a list.
• Displays the names of students with an average greater than or equal to 10.
• Displays the information of the student with the highest average.

5. Write a function save_students(list, filename) that saves the list of students


to a JSON file named "[Link]".

6. Write a function load_students(filename) that reads data from the JSON file
and reconstructs the list of students as dictionaries.

7. Write a function search_student_by_code(code, filename) that searches for a


student in the JSON file based on their code, and returns their information if found.

8. Write a function update_average(code, new_average, filename) that updates


the average of a student searched by their code, then saves the data to the JSON
file.

9. Write a function delete_student(code, filename) that deletes a student iden-


tified by their code, then saves the remaining students to a new JSON file named
"students_updated.json".

6
Algorithms II Problem Set I

Correction
Algorithm
Require: Operations for student management (add, display, save, load, search,
update, delete)
Ensure: Manage student data
Define student dictionary with fields: code,
lastn ame, f irstn ame, gender, averageDef inef unctioninput_student():
Read code, lastn ame, f irstn ame, gender, averagef rominputreturn studentdictionary
Define function display_student(student):
print student details
Define function save_students(list, f ilename): list to JSON file
Define function load_students(f ilename): JSON file and parse into student dictio-
naries
Define function search_student_by_code(code, f ilename): JSON file
for each student in file do
if [Link] == code then
return student
end if
end for
return None
Define function update_average(code, new_avg, f ilename): JSON file stu-
[Link] for matching code updated data back to JSON
Define function delete_student(code, f ilename): JSON file student with matching
code remaining data to "studentsu [Link]”

Python Implementation

7
Algorithms II Problem Set I

Correction

1 import json
2
3 def input_student () :
4 return {
5 ’ code ’: int ( input ( " Enter code : " ) ) ,
6 ’ last_name ’: input ( " Enter last name : " ) ,
7 ’ first_name ’: input ( " Enter first name : " ) ,
8 ’ gender ’: input ( " Enter gender ( M / F ) : " ) ,
9 ’ average ’: float ( input ( " Enter average (0 -20) : " ) )
10 }
11

12 def display_student ( student ) :


13 print ( f " Code : { student [ ’ code ’]} , Name : { student [ ’ first_name ’]}
{ student [ ’ last_name ’]} , Gender : { student [ ’ gender ’]} , Average : {
student [ ’ average ’]} " )
14
15 def save_students ( students , filename ) :
16 with open ( filename , ’w ’) as f :
17 json . dump ( students , f )
18
19 def load_students ( filename ) :
20 with open ( filename , ’r ’) as f :
21 return json . load ( f )
22
23 def s e a rc h _ s t ud en t _ b y _c od e ( code , filename ) :
24 students = load_students ( filename )
25 for student in students :
26 if student [ ’ code ’] == code :
27 return student
28 return None
29
30 def update_average ( code , new_avg , filename ) :
31 students = load_students ( filename )
32 for student in students :
33 if student [ ’ code ’] == code :
34 student [ ’ average ’] = new_avg
35 save_students ( students , filename )
36
37 def delete_student ( code , filename ) :
38 students = load_students ( filename )
39 updated = [ s for s in students if s [ ’ code ’] != code ]
40 save_students ( updated , " students_updated . json " )

8
Algorithms II Problem Set I

Correction

1 # Main program
2 n = int ( input ( " Enter number of students ( n 100) : " ) )
3 students = [ input_student () for _ in range ( n ) ]
4 print ( " \ nStudents with average 10: " )
5 for s in students :
6 if s [ ’ average ’] >= 10:
7 display_student ( s )
8 print ( " \ nStudent with highest average : " )
9 top = max ( students , key = lambda x : x [ ’ average ’ ])
10 display_student ( top )
11 save_students ( students , " students . json " )
12 code = int ( input ( " Enter code to search : " ) )
13 found = s e a r ch _s tu d e nt _b y_ c o d e ( code , " students . json " )
14 if found :
15 display_student ( found )
16 new_avg = float ( input ( " Enter new average : " ) )
17 update_average ( code , new_avg , " students . json " )
18 delete_student ( code , " students . json " )
Listing 2: Python Code for Exercise 2

9
Algorithms II Problem Set I

Exercise 3: Complex Number Manipulation


A complex number Z is fully defined by its real part a and its imaginary part b, and is
written in the form: Z = a + bi
In this exercise, complex numbers will be represented using dictionaries in Python.
They will be stored in a list, which will allow various mathematical operations and ma-
nipulations. This data can also be saved or loaded from a CSV file named "[Link]".
Required work:

1. Declare a complex number using a Python dictionary.

2. Write the following functions:

• realPart(Z): returns the real part of the complex number Z.


• imaginaryPart(Z): returns the imaginary part of the complex number Z.
• Modulus(Z):
√ returns the modulus of the complex number Z, defined by: |Z| =
a +b .
2 2

3. Implement the following arithmetic functions:

• addition(Z1, Z2): returns the sum of Z1 and Z2.


• subtraction(Z1, Z2): returns the difference Z1-Z2.
• multiplication(Z1, Z2): returns the product of Z1 and Z2, according to the
formula: (a + bi)(c + di) = (ac − bd) + (ad + bc)i

4. Write a function conjugate(Z) that returns the conjugate of a complex number Z,


which is a − bi.

5. Write a function inverse(Z) that returns the inverse of a complex number Z, if it


is non-zero: Z −1 = aa−bi
2 +b2

6. Write a function equality(Z1, Z2) that tests if two complex numbers are equal
(same real and imaginary parts).

7. Write a procedure display(Z) that displays a complex number in text form (e.g.,
3 + 4i or 2 - 5i, or just 7 if the imaginary part is zero...).

Now assume we have an array TC containing N complex numbers (N ≤ 100).

8. Display the complex number with the largest modulus in the array TC, then check
if its conjugate is also present in this array.

9. Calculate:

• The sum Zs of all elements in TC.


• The product Zp of all non-zero elements of the array.

10. Calculate the difference Zs - Zp and display the result only if this difference is a
pure imaginary number (its real part is zero).

10
Algorithms II Problem Set I

11. Write a function save_csv(TC, filename) that saves the TC array to a CSV file
named "[Link]", each line containing two values: the real part and the imag-
inary part of the complex number.

12. Write a function load_csv(filename) that reads the "[Link]" file, and returns
a list of dictionaries representing the complex numbers read.

13. After reading the data from the "[Link]" file, display all complex numbers
whose modulus is strictly greater than a given value (entered by the user).

11
Algorithms II Problem Set I

Correction
Algorithm
Require: Operations for complex numbers (add, subtract, multiply, conjugate,
inverse, equality)
Ensure: Complex number arithmetic
Define complex number dictionary: real, imaginary
Define function realPart(Z):
return [Link]
Define function imaginaryPart(Z):
return [Link]
Define function
p Modulus(Z):
return Z.real2 + [Link] 2
Define function addition(Z1, Z2):
return {real : [Link] + [Link], imaginary : [Link] + [Link]}
Define function subtraction(Z1, Z2):
return {real : [Link] − [Link], imaginary : [Link] − [Link]}
Define function multiplication(Z1, Z2):
return {real : [Link] ∗ [Link] − [Link] ∗ [Link], imaginary :
[Link] ∗ [Link] + [Link] ∗ [Link]}
Define function conjugate(Z):
return {real : [Link], imaginary : −[Link]}
Define function inverse(Z):
if [Link] == 0 and [Link] == 0 then
"Zero complex number"
end if
denom ← Z.real2 + [Link] 2
return {real : [Link]/denom, imaginary : −[Link]/denom}
Define function equality(Z1, Z2):
return [Link] == [Link] and [Link] == [Link]
Define function display(Z):
if [Link] == 0 then
print [Link]
else if [Link] > 0 then
print f ”[Link] + [Link]”
else
print f ”[Link] − −[Link]”
end if

Python Implementation

12
Algorithms II Problem Set I

Correction

1 import math
2 import csv
3
4 def real_part ( z ) :
5 return z [ ’ real ’]
6
7 def imaginary_part ( z ) :
8 return z [ ’ imaginary ’]
9
10 def modulus ( z ) :
11 return math . sqrt ( real_part ( z ) **2 + imaginary_part ( z ) **2)
12
13 def addition ( z1 , z2 ) :
14 return { ’ real ’: real_part ( z1 ) + real_part ( z2 ) , ’ imaginary ’:
imaginary_part ( z1 ) + imaginary_part ( z2 ) }
15
16 def subtraction ( z1 , z2 ) :
17 return { ’ real ’: real_part ( z1 ) - real_part ( z2 ) , ’ imaginary ’:
imaginary_part ( z1 ) - imaginary_part ( z2 ) }
18
19 def multiplication ( z1 , z2 ) :
20 real = real_part ( z1 ) * real_part ( z2 ) - imaginary_part ( z1 ) *
imaginary_part ( z2 )
21 imag = real_part ( z1 ) * imaginary_part ( z2 ) + imaginary_part ( z1 ) *
real_part ( z2 )
22 return { ’ real ’: real , ’ imaginary ’: imag }
23
24 def conjugate ( z ) :
25 return { ’ real ’: real_part ( z ) , ’ imaginary ’: - imaginary_part ( z ) }
26
27 def inverse ( z ) :
28 if real_part ( z ) == 0 and imaginary_part ( z ) == 0:
29 raise ValueError ( " Cannot invert zero complex number " )
30 denom = modulus ( z ) **2
31 return { ’ real ’: real_part ( z ) / denom , ’ imaginary ’: -
imaginary_part ( z ) / denom }
32
33 def equality ( z1 , z2 ) :
34 return real_part ( z1 ) == real_part ( z2 ) and imaginary_part ( z1 ) ==
imaginary_part ( z2 )
35

36 def display_complex ( z ) :
37 r = real_part ( z )
38 i = imaginary_part ( z )
39 if i == 0:
40 print ( r )
41 elif i > 0:
42 print ( f " { r } + { i } i " )
43 else :
44 print ( f " { r } - { - i } i " )

13
Algorithms II Problem Set I

Correction

1 # Additional operations for array TC


2 def save_csv ( tc , filename ) :
3 with open ( filename , ’w ’ , newline = ’ ’) as f :
4 writer = csv . writer ( f )
5 for z in tc :
6 writer . writerow ([ real_part ( z ) , imaginary_part ( z ) ])
7
8 def load_csv ( filename ) :
9 tc = []
10 with open ( filename , ’r ’) as f :
11 reader = csv . reader ( f )
12 for row in reader :
13 tc . append ({ ’ real ’: float ( row [0]) , ’ imaginary ’: float (
row [1]) })
14 return tc
15
16 # Example usage
17 z1 = { ’ real ’: 3 , ’ imaginary ’: 4}
18 z2 = { ’ real ’: 1 , ’ imaginary ’: -2}
19 z_sum = addition ( z1 , z2 )
20 display_complex ( z_sum )
21 tc = [ z1 , z2 ]
22 save_csv ( tc , " complex . csv " )
23 loaded = load_csv ( " complex . csv " )
Listing 3: Python Code for Exercise 3

14

You might also like