Professional Documents
Culture Documents
Laboratory Reports: Data Structures and Algorithms
Laboratory Reports: Data Structures and Algorithms
Laboratory
Reports
DATA STRUCTURES
in AND
ALGORITHMS
Submitted by:
Jamaira C. Danao
Submitted to:
Engr. Jay-ar M. Pentecostes
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
SCORE SHEET
LABORATORY
TITLE SCORE
ACTIVITY No.
4 Operators
5 Functions
6 String / List
7 Tuple / Dictionary
If else
8
For loop
While loop
9
Break/Continue/Pass Statements
12 Stacks
13 Queues/ Dequeues
Preorder Traversal/
14 Inorder Traversal/
Postorder Traversal
15 Heaps
TOTAL
LABORATORY REPORT
No. 1
Python Programming Environment
Objectives:
Abstract:
To begin in our first sample code, we should first create a new project showing the
following steps:
Step 1: To create a project, from the main menu, choose File | New Project or If on the
Welcome screen, click New Project.
Step 2: When creating a new project, you need to specify a Python interpreter to
execute Python code in your project. You need at least one Python installation
to be available on your machine.
Step 3: Creating a Python File. In the Project tool window, select the project root
(typically, it is the root node in the project tree), right-click it, and select File |
New.
Step 4: Select the option Python File from the context menu, and then type the new
filename.
After that we will be able to create our first python file where we can input our code.
Sample:
1. Write a program that takes a users’ name and outputs “Welcome, username”.
Method 1: Using Shortcut. Use the shortcut Ctrl+Shift+F10 on Windows or Linux to run
the code.
Method 2: Right click the code window and click on Run ‘add’.
Method 3: Choose ‘add’ and click on the little green arrow at the top right corner of the
screen.
If it detects incorrect code or input, it will raise exceptions and the program immediately
stops.
As you can see, it raises an exception which is Syntax error, as it does not contain
colon in the first line of code.
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT 6
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
Code:
def welcome_message():
name = input("Enter your name: ")
print("Welcome,", name)
welcome_message()
The first sample program created focuses on getting users' names; with only a few lines
of code, we can output a greeting that welcomes the user (“Welcome, user_name”).
From this lab, I understood the basic concept of using a Python IDE, which helped me
create a simple code and run it. Furthermore, it gave me knowledge of how the Python
programming language is used.
References:
Websetup.org (2022). 10 Best IDE Software for Web Development. Retrieved from
https://websetup.org/best-ide-software-for-web-development/
Finxter (n.d.). Writing, Running, Debugging, and Testing Code In PyCharm. Retrieved
from https://finxter.com/pycharm-run-debug-test/
LABORATORY REPORT
No. 2
Keywords, Identifiers, Statements and Comments
Objectives:
Abstract:
KEYWORDS
Sample:
1. Write a program that takes two user inputs, compares them, and prints out
"Password Match" if the inputs match or "Passwords don't match" if the inputs don't
match. The parameters used should be two strings, pwd1 and pwd2.
The methodology used was a comparison between the two inputs to determine if
they matched or not by using ‘==’ equality operator. The results showed whether or
not the passwords matched. During the process only two parameters are needed to
accomplish the program.
2. Write a program that calculates the arithmetic sequence having first term of 2 and
term number of 8 with the common difference of 2.
Given that the problem asks to display the arithmetic sequence of the given input
parameters, which are of integer type and identified as: a 1 (first term), n (term
number), and d (common difference). To provide what is being asked in the
problem, the following mathematical formula will be needed:
an = a1 +(n−1)d
IDENTIFIERS
Sample:
1. Write a program to calculate the net salary of an employee. The program should
take the employee ID and salary as input, deduct 5% of the salary as income tax
and 2% to the salary as loan, then output the net salary of the employee. The given
The problem is to calculate the total net salary of the employee with the following
parameters identified as: income tax (float type), loan (integer type), employee id
(integer type) and salary (integer type). The following mathematical formula:
The product cannot be used as an independent program, but it can be used as part
of a larger program. The results showed that the net salary was accurately
calculated after tax and loan deductions. In conclusion, this code successfully
solved the problem of calculating net salary after tax deductions.
2. Write a program that takes a temperature in Fahrenheit from the user, convert it to
Celsius and return it with two decimal places. The program must take input from the
user in integer type. The Mathematical formula to convert Celsius to Fahrenheit:
STATEMENTS
Python statements are the code instructions that are executed by the Python
interpreter. Python executes statements one by one as they appear in the code. It is
either written in a single line or multi-line statement. (e.g. if statement, for statement,
while statement, etc.)
Sample:
1. Write a program that gets the sum of two numbers identified as num1 -= 5 and
num2 = 10.
The problem is to calculate the sum of two integers taken from the user, the
parameters identified to be num1 and num2. The output of the program is the sum
of the two integers. During the processing or calculation phase, we don’t need any
extra parameters (variables) for this problem.
2. Given two sets of integers with values of, set1 = {4, 5, 3, 2, 6, 9} and set2 = {1, 2, 6,
10, 5, 8, 3}. Write a program to find the common values between the two sets.
The problem is based on the union of sets in which it will find the values that are in
both given parameters. The use of bitwise operator ‘&’ or known as ‘AND’ allow us
to find the common values between the two sets. Hence, the output of the program
is the common values between the two sets.
COMMENTS
Sample:
1. Write a program that prints even numbers in the range of 1 to 10.
The problem is to calculate even numbers from 1 to 10. Even numbers are those
that are divisible by 2. Using the ‘%’ modulo Python operator helps the program to
execute the desired result. Hence, the output of the program is a list of even
numbers (integer type).
2. Write a program that calculates the area of a circle, given that the user will be the
one to input the desired value of the radius.
Codes:
KEYWORDS
Match the Passwords
Arithmetic Sequence
IDENTIFIERS
Net Salary
def Net_Salary():
# Takes inputs from the user
Employee_ID = int(input("Enter your ID: "))
Employee_salary = int(input("Enter your salary: Php"))
Fahrenheit to Celsius
STATEMENTS
Sum of two integers
Sets
# Driver code
set1 = {4, 5, 3, 2, 6, 9}
set2 = {1, 2, 6, 10, 5, 8, 3}
COMMENTS
Even Numbers
i=1
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
11
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
KEYWORDS
Match the Passwords
The goal of the code above was to verify whether two passwords entered by the user
matched. The code first asked the user to enter a password and store it in the variable
'pwd1'. It then asked the user to re-enter the same password and store it in the variable
'pwd2'. Finally, the code will be checked if the two passwords matched by using an if-
else statement. If the passwords matched, the code printed "Password Match". If the
passwords didn't match, the code printed "Passwords don't match".
The results of the code were as expected, when the same passwords were
entered, the code printed "Password Match" and when different passwords were
entered, the code printed "Passwords don't match". If a different method or equipment
had been used, the results may have been different depending on the algorithm.
However, the results of this code correlated with the general theory of the question,
which was to verify whether two passwords entered by the user matched.
Arithmetic Sequence
Based on the problem, it is given to find the arithmetic sequence on the given values
from 2 to 9. The program uses for loop that contains the sequence of number inside it,
the variable ‘arithmetic_seq’ stores the formula in calculation of the arithmetic
sequence: first term + (term number -1) * common difference. So, during each loop it
will automatically output the numbers of our arithmetic sequence. Using a different
method could result in same output as it follows the format in the problem. Finally the
code was successfully able to output the arithmetic sequence of numbers.
IDENTIFIERS
Net Salary
I was trying to figure out the net salary of an employee after the deductions of income
tax and loans. To do so, I created a function that asks the user to input the employee ID
and salary, and then calculate the net salary after the deductions. After running the
code, the results showed that the net salary is the initial salary minus 5% of it for income
tax and 2% of it for loan. My hypothesis was true, as the results showed that the
deductions are as expected. If I had used a different method or equipment, the results
would have been the same, as the deductions are always the same, regardless of which
method or equipment is used.
Fahrenheit to Celsius
After entering a Fahrenheit temperature as user input and using the formula to convert
the temperature into Celsius, I have successfully achieved the goal of writing a code to
convert Fahrenheit temperature to Celsius. My hypothesis that the code would work
correctly was proven to be true. The results were as follows: when I entered a
Fahrenheit temperature, it was converted to a Celsius temperature and printed with two
decimal places. The code works by first taking the user input in Fahrenheit, then
subtracting 32 from it and multiplying by 5/9. Finally, the new Celsius temperature is
printed with two decimal places. If I had used a different method or equipment, the
results may have differed. However, the results do correlate with the general theory of
the question as the formula used to convert temperatures is the same theory used in
general.
STATEMENTS
Sum of two integers
The goal of the code was to add two integers, in this case 5 and 10. The code line by
line is as follows: First, a function is defined that adds two integers together. Then the
variables 'num1' and 'num2' are set to 5 and 10 respectively. Finally, the sum of these
two integers is returned and printed, which is 15. The hypothesis that the code would
successfully add two integers was proven to be true. The results of this code correlate
with the general theory of adding two integers together, which is that the sum of the two
integers should equal the result.
Common Elements
The goal of the code was to identify values that are present in both sets. By using the
‘&’ operator, the intersection of the two sets was determined and printed. The result was
{2, 3, 5, 6}, showing that the values 2, 3, 5 and 6 are present in both sets. This
hypothesis was true, and the results correlated with the general theory of the question.
If a different method or equipment had been used, the same result would have been
produced as the intersection of two sets is always the same regardless of approach.
COMMENTS
Even Numbers
The goal of this code is to print all the even numbers from 1 to 9. To achieve the goal, I
used a while loop to iterate through each number and an if statement to check if the
number is even. Starting with the variable 'i' set to 1, the while loop will continue to
execute until i reaches a value of 9. Inside the loop, the if statement will use modulo (%)
operator to check if the number is even. If the number is even, it will be printed. When
the while loop ends, all even numbers between 1 and 9 will have been printed.
My hypothesis was true. The code printed all even numbers from 1 to 9 as expected. If I
were to use a different method or equipment, I could use a for loop with a range from 1
to 9 and apply the same if statement to check if the number is even. The results would
be the same. The results of this code are in line with the general theory that it is
possible to print all even numbers between 1 and 9 using a while loop and if statement.
The program was to calculate and output the area of a circle given the radius. My
hypothesis was true, as the code successfully calculated and output the area of the
circle. The code first asked the user to input the radius of the circle, which was then
stored in the variable radius as a float. Then, the area of the circle was calculated using
the formula: 3.14 * radius^2 and was outputted to the user. If a different method or
equipment was used, the results would likely be different as the calculation formula
would also be different. However, my results correlate with the general theory of this
question since I used the correct formula for calculating the area of a circle.
To wrap it all up, I have learned that keywords are predefined words in Python
that have special meaning and cannot be used as identifiers; identifiers are names
given to variables, functions, classes, and other objects; comments are used to explain
code and are ignored by the Python interpreter; and statements are commands that are
used to execute code in Python.
References:
Downey, A. (2012). Think Python: How to Think Like a Computer Scientist (Version
2.0.17). Needham, Massachusetts: Green Tea Press. Retrieved from
http://www.thinkpython.com
LABORATORY REPORT
No. 3
Variables, Data Type Conversion
Objectives:
Abstract:
VARIABLES
Sample:
1. Write a program that shows the growth of population using a graph chart with the
given data values data = [77.99, 79.67, 81.37, 83.05, 84.71, 86.33, 87.89, 89.41,
90.90, 92.41, 93.97, 95.57, 97.21, 98.87, 100.51, 102.11, 103.66, 105.17, 106.65,
106.65, 108.12) and years between 2000-2020. The given values should be in an
animated graph.
The problem was to create a graph that would show population growth over a
period of 21 years. The input parameters are identified as list type: data and years.
The program used the animation module from matplotlib to create the graph, as it
allowed us to animate the population growth over the 20-year period in the
Philippines. The results of the program show a graph with a steady increase in
population growth over the 20-year period, with the population increasing from
77.99 million to 108.12 million.
The problem was to create a program that could generate a random title for a
capstone project. This product can be used as an independent program, as it is able
to generate a random title without any user input or to help narrow down a list of
potential titles. The methodology used was to create two lists of words, one for
nouns and one for verbs, and then randomly select one word from each list to
create the title. The program successfully shows the desired output.
Sample:
1. The war battleship is under attack and the captain needs to send a message to
another ship for reinforcements. The commander officer instructed you to create the
message encoded in sentences and carry them out as soon as possible. Write a
program to make it confidential, the first letter of each word contains a message.
And will be in form of hexadecimal value. Write a program that takes input from the
user, and the first letter of each word must be extracted and converted.
The problem was to take a string of text from the user and convert the first letter of
each word into hexadecimal values. The methodology used was to split the string
into a list of words, create a list to contain the first letter of each word, iterate over all
words in the list, select the first letter of each word, and append it to the list, and
then rejoin the letters. The output of the program is a list containing the
corresponding values of the letters in hexadecimal. The program can be used as an
independent program, as it takes a string of text as input and outputs a list of ASCII
characters.
2. The bank manager is worried about the security of the bank's information and wants
to encrypt the data before it is sent to the main server. Write a program to encrypt
the data. The data should be encrypted in (EBCDIC) Extended Binary Coded
Decimal Interchange Code, including should be in 8 bit-configuration and its total
bits. The message should be encrypted in such a way that the binary conversion of
each character should be the same for both encrypting and decrypting.
The program is to convert input from Extended Binary Coded Decimal Interchange
Code (EBCDIC) having its input parameter identified as string type. The output of
the program is to display the converted value in EBCDIC, its corresponding 8-bit
values and the total bits. During the processing, extra parameters (variables) are
needed to store the different values ask by the problem. The result of the program is
the converted value from EBCDIC, binary values of letter and the calculated total
bits of the input.
Code:
VARIABLES
Population Graph
# Data Values
data = [77.99, 79.67, 81.37, 83.05, 84.71, 86.33, 87.89, 89.41, 90.90, 92.41, 93.97,
95.57, 97.21, 98.87, 100.51, 102.11, 103.66, 105.17, 106.65, 106.65, 108.12]
# Years
years = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
# Plot settings
plt.title("Population Growth")
plt.xlabel("Year")
plt.ylabel("Population (in billions)")
# Create animation
def init():
line.set_data([], [])
return line,
def animate(i):
x = years[:i+1]
y = data[:i+1]
line.set_data(x, y)
return line,
plt.show()
Capstone Title
import random
# List of nouns
nouns = ["Data", "Technology", "AI", "Research", "Analysis", "Programming",
"Design",
"Development", "Systems", "Software", "Security", "Networking", "Cloud",
"Robotics", "Hardware", "Web", "Mobile", "Database"]
# List of verbs
verbs = ["Exploring", "Enhancing", "Developing", "Designing", "Implementing",
"Analyzing", "Testing", "Managing", "Optimizing", "Integrating",
"Deploying", "Securing", "Automating", "Innovating"]
# Takes input
Text = str(input("Enter Text: "))
List_of_Words = Text.split()
print("Letter: \n",Convert_toAscii)
print(First_Letters)
Bank’s Data
# Define function to go through each letter and get the equivalent binary
def get_bit_length(text):
binary_text = text_to_ebcdic(text)
bit_length = 0
for letter in binary_text:
bit_length += len(letter)
return bit_length
VARIABLES
Population Graph
The program is about a population growth through the years. The goal of this code was
to create a graph to show population growth over a period of 21 years. The hypothesis
was that the population would grow steadily over time. The results showed that this was
indeed the case. The code begins by importing the necessary modules for plotting and
animating the graph. Next, the data values and years are stored in two separate lists.
The plot settings are then customized, including the title, x- and y-axes labels. Figure
and axes objects are then created and the x- and y-limits are set. The line is initialized.
The animation is then created. The init() function is called first in order to initialize the
line. The animate() function is then called to update the line with the data and years
stored in the respective lists. The graph is then designed using the FuncAnimation()
function, which takes the figure, animate function, init function, frames and interval as
arguments. The results showed that the population has grown steadily over the 21-year
period, with an average growth rate of 1.27 billion people per year. If a different method
or equipment was used, the results may not have been the same. However, the results
do correlate with the general theory that the population has grown steadily over the 21-
year period.
Capstone Title
The program generates a random title for a capstone project by choosing a random
verb from a list of verbs and a random noun from a list of nouns, then concatenating
them with the word "Capstone". The goal of the code is to randomly generate a title for
a capstone project. The hypothesis is that the code will generate a random, unique title
each time it is run. The results of running the code will vary each time, as the verb and
noun chosen are random. The code uses the Python random module to randomly
choose an item from a list. In conclusion, the results do correlate with the general theory
of randomness. If a different method or equipment was used, such as manually
selecting verbs and nouns, the results would not be random.
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
19
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
The given code is a program which takes a user input in the form of sentences, and
extracts the first letter of each word in the sentence, and then converts it into a
hexadecimal value. The input taken from the user in the form of a string and stores it in
the variable 'Text', then splits the string into words and stores it in the list
'List_of_Words'. An empty list named as 'List_of_Letters' will be responsible to store the
first letter of each word. To extract the first letter of each word the program will iterate
through the list 'List_of_Words' and append to the list 'List_of_Letters'. After that, the
extracted letter will be rejoined and stored in the variable 'First_Letters'. Lastly, inside
the variable 'Convert_toAscii' contains the code in which the values in variable
'First_Letters' will be converted into a hexadecimal values and printed them out. If other
methods or equipment were used, the results could be different.
Bank’s Data
In this code, the input was a plain text from the user which is then encoded using the
(EBCDIC) Extended Binary Coded Decimal Interchange Code . The program imports
the required modules and initializes an empty string ‘encoded_str’, string type. Then the
program gets the input of plain text from the user with a variable name ‘ plain_text’ and
loops through all the characters. For each character, the program converts it to the
ASCII code, then to the EBCDIC value, and lastly to a character. The program also
defines a function named ‘text_to_ebcdic’ to convert each character’s bit configuration
to binary and appends the binary value to a ‘result’ list. This list is then returned. The
program also defines a function named ‘get_bit_length’ to get the equivalent binary of
each letter and adds the bit length of each letter. Lastly, the program prints the
equivalent bit configuration and the number of total bits and displays the encrypted text
in EBCDIC code.
The goal of this code was to encrypt the plain text from the user by converting
each character to the EBCDIC value. The hypothesis was true since the code was able
to encrypt the plain text and display the encrypted text in EBCDIC value. The results
were step-by-step as the program looped through each character, converted it to the
ASCII code, then to the EBCDIC code.
This lab taught me how to use variables to store and retrieve data, as well as
how to convert values in different data types. I also learned how to use built-in functions
for data type conversion, and how to create programs to generate random titles and
encrypt data. And as well as to use the animation module from matplotlib to create
animated graphs.
References:
Pynative.com (n.d.). Python Functions Exercise with Solution [10 Programs]. Retrieved
from: https://pynative.com/ python -functions-exercises-solutions/
thisPointer. (2020). Get first letter of every word in String in Python. Retrieved from:
https://www.thispointer.com/python -get -first-letter-of-each-word-in-a-string/
LABORATORY REPORT
No. 4
Operators
Objectives:
Abstract:
Sample:
1. An amusement park has installed a Ferris wheel with its radius of 15 meters. In order
to paint the wheel, the park needs to calculate the area of the sector of the wheel in
order to determine the amount of paint needed. Assume that the angle of the sector
is 45 degrees. Write a program that calculates the sector area of the wheel.
The problem is to calculate the area of a sector of a circle having its inputs
parameters identified as: radius (integer type), angle (integer type) and pi (float type).
The output of the program is to display the area; hence the output parameter is
identified as sur_area (float type). During the processing or calculation phase, we
need extra parameter (variables) for this problem, pi. The area of the sector is the
multiplication of pi, radius square and angle divided by 360, hence the mathematical
formula to calculate area is:
Sector Area = pi *(radius)2 *(Angle/360)
2. Write a Program to calculate and display all the least common multiples of two
numbers, x and y taken from the user. The least common multiple of two numbers is
the smallest number that is divisible by both numbers.
The problem is to calculate the common multiples of two given inputs parameters
identified as: x (integer type) and y (integer type). The output of the program is to
display all the common multiples; hence in process the program needs extra
parameters (variables) identified as i (integer type). The program uses a loop to go
through the range of numbers from 1 to 100. Hence, the result shows the least
common multiple of two input in range of numbers from 1 to 100.
Code:
Sector Area
def sector_area():
pi=22/7
# assign the given value to the radius and angle
radius = 15
angle = 45
# check if the angle exceeds 360
if angle >= 360:
print("Angle is exceeds to its measurement")
return
# calculate the area of the sector
sur_area = (pi*radius**2) * (angle/360)
print("Sector Area: ", sur_area)
# Call the function
sector_area()
Sector Area
This program is written to calculate the area of a sector of the Ferris wheel. The
parameters of this problem are the radius, angle, and surface area. The hypothesis of
this problem is that the surface area of the sector can be calculated and displayed. To
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
23
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
begin, the given value for the radius and angle were assigned. The program then
checks if the angle exceeds 360. If it does, it prints an error message and returns. If not,
the area of the sector is then calculated using the given equation for surface area.
Finally, the program calls the function named as ‘sector_area()’ which contains the
calculation process and prints the surface area. The goal of this program was achieved,
and the hypothesis was proven to be true. If a different method or equipment was used,
it is possible that the same results could have been achieved. The results of this
program correlate with the general theory of this question as it correctly calculates the
surface area of the sector and displays it.
The problem is to find the least common multiple of two numbers. The input variables
are num1 and num2, both of which are integer inputs from the user. The variable
list_of_nums list holds the range of numbers from 1 to 100, and the variable lcm_list list
holds the least common multiple. The code iterates through the list of numbers and
checks if the number is divisible by both num1 and num2. If the number is divisible, it is
appended to the lcm_list list. The least common multiple is then printed.
Upon running the code, the goal of finding the least common multiple of two
numbers was achieved. The hypothesis was true, as the smallest number divisible by
both numbers was identified and printed. The results of the code were found step by
step, as the code iterates through the range of numbers from 1 to 100 and appends the
divisible numbers to the lcm_list list. Once all the divisible numbers are appended, the
min() function is used to identify the smallest number in the list, which is then printed. If
another method or equipment were used, the results may vary. However, the results of
this code would remain the same regardless of different methods and equipment used.
References:
Goodrich, M. T., Tamassia, R., & Goldwasser, M. H. (2013). Data Structures and
Algorithms in Python. John Wiley & Sons, Inc.
LABORATORY REPORT
No. 5
Functions
Objectives:
Abstract:
Sample:
1. A young kid was given an amount of time to practice playing piano in preparation for
the upcoming event. Given the dates from November 28, 2022, to February 14,
2023, create a program that calculates how many days are left for the kid to
practice.
The problem is to determine the range of date between the two given values. The
program creates a function that takes two dates as parameters and returns the
number of days between them. The product can be used as an independent
program, as it is a standalone function. We used the datetime module to access the
date class, which allowed us to store the dates in a range. The results of the
program are the number of days between the two given dates, which is 78 days.
The problem was to find the equivalent electron charge of a given value of
coulombs. The problem was solved by creating a function that takes the value of
coulombs as an input and returns the equivalent electron charge. This product can
be used as an independent program. The methodology used was to create a
function that takes the value of coulombs as an input and returns the equivalent
electron charge. The results showed that the equivalent electron charge of a given
value of coulombs can be calculated using this function.
Code:
Electron Charge
The program is focused on determining the number of days between November 28th,
2022 and February 14th, 2023. The code does this by making use of the datetime
library and a function, num_days, which subtracts the value of varaible date_two from
date_one. The code first imports the date library, and then defines the num_days
function, which is used to calculate the number of days between the two dates. The
code then stores the two dates in the range of date_one to date_two and prints the
result. Hence, number of days between the two dates is 78 days. To analyze what
would happen if you used a different method or equipment, it would depend on the
context and type of analysis being performed. For example, if you were comparing
calendars, then using a different method or equipment would likely yield the same result
as the code provided. However, if you were trying to compare different types of data,
then using a different method or equipment may be necessary.
Electron Charge
The given code is a function that finds the equivalent electron charge of a given value of
Coulombs. By inputting the desired value of Coulombs, it calculates the equivalent
electron charge and prints the solution. It starts by defining a function
electron_charge(coulomb) to find the equivalent electron charge of the input. Then it
reads in the value of Coulombs, calculates the equivalent electron charge, and prints
the solution. The results of the code can be seen step by step by running it with a given
value of Coulombs. However, different methods or equipment may yield different
results. For example, if the value of Coulombs is determined using a different method,
the results may be different. Additionally, if different equipment is used for calculating
the equivalent electron charge, the results may vary. Therefore, it is important to
consider the method and equipment used when calculating the equivalent electron
charge.
References:
Python datetime Module - Python datetime Class (2021, April 28). GeeksforGeeks.
https://www.geeksforgeeks.org/python-datetime-module/
LABORATORY REPORT
No. 6
String and List
Objectives:
To understand the basic syntax for manipulating strings and lists in Python.
To learn how to create, access, and modify elements in strings and lists.
Abstract:
Python is a powerful programming language that provides many tools for working
with strings and lists. Strings are sequences of characters that are used to store and
manipulate text. Lists are collections of items that can store data of any type, including
strings, numbers, and other objects. Both strings and lists can be manipulated using a
variety of methods and functions, making them versatile and useful for many
programming applications.
STRING
Sample:
1. Write a program that count the vowels of the given string "Peter Picked a Peck of
Pickled Peppers".
This concept is important because it allows us to quickly and easily count the
number of vowels in a given string. The problem was to find a way to count the
number of vowels in a given string. The program used by creating a function that
takes two inputs, a string and a list of vowels, and then the output (integer type) is
the total number of vowels in the string, that is 11. We used a list comprehension
methodology to create a list of all characters in the input string that are also in the
list. Hence, an extra parameter is used during the processing phase of the program.
2. Aliza has a string of characters, "This is a string". He wants to reverse the string and
print the result. Write a program that can take the string as input and output the
reversed string.
The problem is to reverse the order of the given string. The methodology used was
to use the len() function to find the index of the last character in the string and then
use a while loop to add the characters in the string to a new variable in reverse
order. This was chosen because it is a simple and efficient way to reverse a string.
This product can be used as an independent program. The result of the program
successfully achieved the desired output. In conclusion, this concept important
because it allows us to reverse a string, which can be used for a variety of
applications.
LIST
Sample:
1. Write a program that can take a list of grades as input and output the average. The
program must determine whether the student has passed or failed for the semester.
The problem was to calculate the average of a student's grades and determine if
they have passed or failed. To solve this problem, I used a loop to iter ate for the
number of subjects and append the grades to a list. Then, I calculated the sum and
average of the grades and checked if the calculated average is passed or failed.
During the calculation phase, extra parameters are used. Hence, the results
showed that the average of the grades was calculated identified to be an integer
type, and it was determined if the student had passed or failed.
2. An amateur statistician and has recently been studying the median of a set of
numbers. He has created a list of five numbers Num_list = [32, 42, 46, 46, 54] and
is eager to find the median of the set. Write a program to calculate the median of
the list using the statistics module.
The problem was to calculate the median of a given list of numbers. The program
used the statistics module in Python, which provides functions for calculating
mathematical statistics of numeric data. Our product can be used as an
independent program, as it is a simple code that can be used to calculate the
median of a given list of numbers. The result of the code was that the median of the
given list of numbers was 46. Therefore, we can conclude that the code was
successful in calculating the median of the given list of numbers.
Code:
STRING
Vowel Count
# Driver Code
string = "Peter Picked a Peck of Pickled Peppers"
vowels = "AaEeIiOoUu"
Check_Vow(string, vowels);
a = "This is a string"
b = ''
print("Result = ", b)
LIST
Passed or Failed
Median
import statistics
# Create a list
Num_list = [32, 42, 46, 46, 54]
STRING
Vowel Count
This program is focused on determining how many vowels does the given has. By
defining a function that takes two inputs, a "string" and a set of "vowels". The function
creates a list of characters in the input string and prints out the length of that list. This
helps to determine the number of vowels in the string. The driver code is used to test
the function by providing a string and set of vowels. Hence, the output contains 11
vowels. This code is useful for anyone who needs to quickly find and count the number
of vowels in a string.
From the problem, it can be concluded that the program should be designed to reverse
a string. The program takes the string 'a' and finds the index of the last character. It then
starts a loop that runs if the index 'i' is greater or equal to 0, adding the character at
index 'i' in string 'a' to the variable 'b' and decrementing the index 'i' by 1 each time. The
result of the reversed string is then printed ‘gnirts a si sihT’.
LIST
Passed or Failed
Based on the problem, it requires to calculate the average grade of the student and
determine whether it is passed of failed the semester. The code first prompts the user to
enter the number of subjects and then to enter the grades for each subject. The grades
are then stored in a list called ‘Grades’ and the sum and average of the grades are
calculated and displayed. The program then checks if the calculated average is above
or below 75 and prints "Passed" or "Failed" accordingly.
Median
The given problem is set to determine the median of the given list of numbers. To solve
the problem, first, the list of numbers needs to be sorted in ascending order, and then
the median can be calculated. The median can be calculated using the median()
function in the statistics module. The median of the set of numbers is 46, which can be
verified by using the median() function.
References:
LABORATORY REPORT
No. 7
Tuple and Dictionary
Objectives:
Abstract:
TUPLES
Sample:
1. Write a program to calculate take two inputs and display the Euclidean distance
between two points, identified by their coordinates (x 1, y1) and (x2, y2).
The program is to take two inputs from the user (tuple type) identified as point1
(integer type) and point2 (integer type). The output of the program is to display the
Euclidean distance; hence the output parameter is identified as distance (float type).
During the processing or calculation phase, we will need extra parameters
(variables) for this problem; input_tuple1, input_tuple2 and distance. The Euclidean
distance between two points can be calculated using the formula:
√ 2
Distance = ( x 2−x 1 ) + ( y 2− y 1 )
2
2. To allow a person to purchase a product with discount, the owner of the store
requires the customers to register their gift card number. Create a program will take
amount of ID to be registered and list of ID numbers.
The program takes two inputs from the user (integer type) which are the quantity of
ID to be registered and the list of ID numbers. It should allow the user to enter
multiple ID numbers and store them in the tuple. The output parameter is identified
as store (tuple type). The output successfully print out the list of ID numbers that
have been successfully registered.
DICTIONARY
Sample:
1. Write a program about a quiz that shows an age problem; Kevin is 4 years older
than Margaret. Next year Kevin will be 2 times as old as Margaret. How old is Kevin
and Margaret. The program must take user’s input as the answer and display if it is
correct or not. Assume that Kevin’s age is 7 and Margaret is 3.
The problem is to take two user inputs (integer type) as an answer to the given age
problem. Then checks if the answers do match in values stored in dictionary. The
output will then print if the user got the correct answers in each input else wrong.
2. Write a program that take user input (string type) which is a movie genre and
outputs its corresponding movies (options = options = {"Comedy": "The Red Notice",
"Adventure": "Miss Peregrine's", "Horror": "Orphan", "Science Fiction": "The Adam
Project", "Historical": "Dunkirk"}) stored in dictionary.
The problem was to create a program that would allow a user to input a search
query and output the title of the most popular movie in that genre. This was solved
by creating a dictionary with 5 key-value pairs and prompting the user to enter a
search query. Using the dictionary, the results were that the program was able to
print the value associated with the key the user entered or "Not found" if no key was
found.
Code:
TUPLES
Distance Between Two Points
import math
# Gets input from the user contain 2 int each splitted by space
point1 = input("Enter x2|y2 values separated by space: ")
point2 = input("Enter x1|y1 values separated by space: ")
DICTIONARY
Age Problem
def code():
# dictionary contains the 2 key-value pairs for the answer
age = {"Kevin": 7, "Margaret": 3 }
print("Question: \n Kevin is 4 years older than Margaret. Next year Kevin will be
2 times as old as Margaret.\n How old is Kevin and Margaret?")
Movie Search
TUPLES
Distance Between Two Points
The problem is used to calculate the distance between two points using Euclidean
distance formula. It begins by importing the math library, which allows us to use the
math functions for calculations. Then it prompts the user to enter point2 containing x 2
and y2 values and point1 containing x1 and y1 values, which will be used to calculate the
distance between the two points. The code then creates two tuples from the inputs,
followed by the calculation of the distance between the two points using the math.sqrt
function an output the calculated distance. The hypothesis that this code tests is that
the distance can be accurately calculated using the math.sqrt function. The result of this
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
35
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
code shows that the distance can be accurately calculated and displayed with two
decimal places. Using different method or equipment, the results may vary depending
on the accuracy of the method or equipment. However, the general theory of
calculating the distance between two points remains the same, regardless of which
method is used.
The code written is focused gift card registration. This is done by taking the quantity of
ID to be registered by the user which is stored in a variable named num. After that an
empty tuple is created named ‘store’ to hold the following IDs to be registered. Then, a
for loop is created to loop through the number of IDs that are to be entered, prompting
the user to enter each ID. The inputted IDs are added to the tuple store. The result is
that the tuple of registered IDs is printed out. If a different method or equipment is used,
the same goal may have been achieved but the code structure may be different. In
conclusion, the results correlate with the general theory because it showed that the IDs
were successfully stored in a tuple.
DICTIONARY
Age Problem
This code is designed for the user to solve the age problem. It asks "Kevin is 4 years
older than Margaret. Next year Kevin will be 2 times as old as Margaret. How old is
Kevin and Margaret?". The program now takes the user's input as the answer, the
answer is stored in a dictionary with two key-value pairs for the age of Kevin and
Margaret. Then checks the input with the age in the dictionary. If the answer matches
the age in the dictionary, it will display that the user got the correct ages. If the answer
doesn't match, it will display that the age is wrong. Finally, the code is called, and the
result is displayed. The solution for the problem is achieved through by some
mathematical calculation:
If other methods were used, the results may be similar depending on the method.
However, if different equipment were used, the results may differ. The results of this
code correlate with the general theory of this problem as it displays whether the answer
is correct or not.
Movie Search
The code processes a user input and searches for the corresponding value in a
dictionary. The dictionary "options" has five key-value pairs, with the keys being the
different genres and the values being the corresponding movie titles. The user is
prompted to enter a search query, which is stored in the variable "enter". The code then
searches the dictionary for the value associated with the key entered by the user and
prints it out. In this case, if the user enters "Comedy" as the search query, the code will
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
36
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
print out "The Red Notice" as the output. If the user enters a genre that does not exist in
the dictionary, it will print out "Not found". To determine if the code has achieved the
goal, we can compare the result to the expected output. This goal has been achieved,
since the code prints out the desired output. If a different method or equipment was
used, the result would likely be different. For example, if a list was used instead of a
dictionary, the code would likely return an error, since the list does not contain key-value
pairs.
References:
Downey, A. (2012). Think Python: How to Think Like a Computer Scientist (Version
2.0.17). Needham, Massachusetts: Green Tea Press
LABORATORY REPORT
No. 8
If Else and For Loop
Objectives:
To understand how to use If Else and For Loop statements in Python to control
program flow and create efficient code.
Be able to identify and implement appropriate If Else and For Loop statements in
Python to solve basic programming problems.
Abstract:
IF ELSE
Sample:
1. Write a program to take input of date of birth from a user and determine their zodiac
sign, lucky colors and provide a piece of advice. The program should print an error
message if the user inputs an invalid date.
The problem is to provide information about the user’s zodiac sign based on their
date of birth, which the parameters identified as: month (integer type) and day
(integer type). The problem was solved by creating a series of conditionals that took
in user input and output the corresponding zodiac sign, lucky colors, and advice.
This program can be used as an independent program and the decision-making
methodology was used to create the conditionals. Hence, the output of the are the
user's zodiac sign, lucky colors, and advice.
2. Write a program based on a card game called “Blackjack”, the input should let the
user to choose if will hit or stay. The rules is to get higher summation of the random
generated numbers that is not greater than 21.
FOR LOOP
Sample:
1. Write a program that shuffle the letter of each word in the list then ask the user to
guess the shuffled word generated from the list. The words that will be stored in the
list are, skeleton, nicotine, continent, and metamorphosis.
The problem was to create a program that randomly shuffles the letters of each
word in the list, and then prompts the user to guess the correct word. The program
was designed to loop until the user enters the correct answer. And yes, the product
can be used as an independent program. The methodology used was a for loop that
iterated through each word in the list, and to use the random module to shuffle the
letters. The results showed that the user was able to correctly guess the words in
the list.
2. You are on a 5-hour sea voyage. The ship sails at a speed of 45 km per hour. Write
a program that will output how many kilometers the ship has traveled by each hour.
The program must be shown in a graph.
The problem is to generate a set of coordinates in graph and show how much the
ship sails through each hour. This was accomplished by creating a loop that iterates
through a range of numbers and then stores the results of the loop in two different
lists. The product can be used as an independent program because all the
necessary functions are included in the code. Furthermore, this concept allows the
user to visualize data in a graphical form using the matplotlib library and numpy
array. The methodology used was to create an array of x and y values using numpy,
and then to plot them using the matplotlib library. And the results of the program are
a graph that plots the x and y values as a scatter plot. Conclusions can be made by
looking at the graph, such as how the relationship between the two variables
changes.
Code:
IF ELSE
Zodiac Sign
print("Welcome!")
# Determines zodiac sign, lucky colors and some advice for the user
# For month of March 21 to April 19
if month == 3 and day >= 21 or month == 4 and day <= 19:
z_sign = "Aries"
print("Your Lucky Colors: Red and White")
print("Be bold and take risks!")
Blackjack
import random
for i in range(2):
player_hand.append(random.randint(1, 10))
dealer_hand.append(random.randint(1, 10))
# Game loop
while player_score <= 21 and dealer_score <= 21:
choice = input("Hit or stay? ").lower() # ask player to hit or stay
else:
print("Dealer wins!")
FOR LOOP
Guess the Words
# Initializing a list
my_list = ["SKELETON", "NICOTINE", "CONTINENT", "METAMORPHOSIS"]
correct_words = 0 # Initializing a variable
Sea Voyage
IF ELSE
Zodiac Sign
The code is designed to ask the user for their date of birth and show information of their
zodiac sign and lucky colors, as well as advice. First, the user is prompted to input their
month and day of birth. The code then checks if the input is within its range, and if not, it
exits with an error message. Following that, the code utilizes a series of if-statements to
determine the user's zodiac sign, lucky colors, and advice based on the given month
and day. Lastly, the information is outputted, displaying the user's zodiac sign and lucky
colors, as well as some advice. If a different method or equipment was used, the results
would be the same. The results of this code correlate with the general theory of
astrology, as each zodiac sign has its own set of lucky colors and associated advice.
Blackjack
The program is focused on a card game Blackjack. It initializes the player and dealer's
hands with two random numbers from 1 to 10. The scores are then displayed and
calculated. The code then enters a game loop where the player is asked to hit or stay. If
the player hits, a new random number is added to the player's hand and the score is
recalculated. If the player stays, the same process is done for the dealer's hand. After
the loop, the scores are compared, and the winner is determined depending on the
conditions. If both scores are above 21, it is a draw. If the player's score is above 21 or
the dealer's score is 21, the dealer wins. If the dealer's score is above 21 or the player's
score is higher than the dealer's or the player's score is 21, the player wins. The output
will show the player's and dealer's hands and scores after each turn, also the winner of
the game depending on the conditions. Hence, the results of this code accurately reflect
the general theory that the winner of a card game is determined by comparing the
scores of the player and dealer.
FOR LOOP
Guess the word
The program allows the user to guess a series of words that have been randomly
shuffled. It begins by initializing a list that contains the words that the user needs to
guess. Then, it imports the random module to allow it to shuffle the letters of the words
in the list. After that, it creates a loop that goes through each word in the list and
shuffles the letters of the word. It then asks the user to guess the word and provides
feedback if their guess is incorrect. The loop continues to ask the user for an answer
until they guess the word correctly. If the user guesses the word correctly, the variable
'var' is incremented by one. Overall, results successfully allowed user to input amount of
tries to guess the word. If a different method or equipment had been used, the results
may have been different. However, in this particular case, the code provided the desired
results.
Sea Voyage
The goal of this code was to create a graph of how many kilometers the ship had
traveled in each hour in 5-hour sea voyage. The hypothesis was that the ship would
travel 45 km per hour, and this proved to be true. The code created a list of x and y
values, with the x values being the hours of the voyage and the y values being the
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
43
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
respective kilometers traveled. The for loop is used to create a loop from 1 to 5, and
multiplied each index value by 40, representing the 45 km/hr speed of the ship. The x
and y lists were then converted to numpy arrays and plotted with a scatter plot, which
showed the expected results of the ship traveling 45 km per hour for 5 hours.
If another method or equipment was used, such as a GPS, the results might be
slightly different due to GPS accuracy. However, the results should still be relatively
close to the results produced by this code, as the speed of the ship should remain
relatively constant. The results of the code correlated with the general theory of the
question, as it showed the ship traveling 45 km per hour for the 5-hour voyage.
References:
Blackjack.org. (2022). How to Play Blackjack: Your Quick Guide for 2022. Retrieved
from https://www.blackjack.org/blackjack-rules/ Matplotlib.pyplot.scatter (2020).
Wikihow.com. (n.d.). The Most and Least Common Zodiac Signs & Their Birthdays.
Retrieved from https://www.wikihow.com/Find-Your-Zodiac-Sign
Kidadl. (n.d.). 30+ Zodiac Quotes To Capture Every Star Sign. Retrieved from
https://www.kidadl.com/articles/zodiac-quotes-for-every-star-sign
LABORATORY REPORT
No. 9
While Loop, Break, Continue, and Pass Statements
Objectives:
To develop the ability to logically construct and analyze While Loops with Break,
Continue, and Pass Statements in Python.
To understand the syntax and basic usage of While Loop, Break, Continue, and
Pass Statements in Python.
Abstract:
WHILE LOOP
Sample:
1. Create a program to simulate the behavior of a traffic light at an intersection. The
light should cycle from green to yellow to red and back to green, with each colour
staying lit for 10 seconds.
The problem was to create a simulation of a traffic light changing from green to
yellow to red and then back to green again. The code successfully solved the
problem by looping through 3 states with a 10 second delay in between each state.
This concept is important as it demonstrates the use of a while loop in order to
create a traffic light simulation. The code can be used as an independent program,
and a while loop was used as it is an effective way to create a loop that runs
continually until a given condition is met. The results of the code demonstrate a
successful simulation of a traffic light changing from green to yellow to red and then
back to green again.
The problem is to take input from the user (integer type) and determine the given
input if it is a Disarium number. The solution was to create a function that uses a
while loop to calculate the length of the given number and then use that to calculate
the sum of the digits powered with their respective positions. The product can be
used as an independent program, using the iterative methodology. The results and
conclusions show whether the number is a disarium number or not.
BREAK
Sample:
1. Create a program that will give the user a random addition math problem and the
user must answer it within 5 seconds, or the game is over. The game should keep
track of how many questions the user got correct and give a final score when the
game ends. The program must generate a random number from 5 to 20.
The problem was to generate two random numbers within a given range and ask
the user to input the sum of these numbers. The code solved this problem by using
the random, time and input modules of Python to generate the random numbers, set
the time limit and get the user input, respectively, also an extra parameter is used to
store the user’s scores. The product can be used as an independent program and is
built on the procedural programming methodology, which uses a sequence of
instructions to solve the problem. The results show that the code was able to
generate the random numbers and set the time limit, and upon getting the user
input, it was able to validate the answer with the right output.
The problem was to create an authentication test that requires the user to answer
three questions to access their information. The program used a while loop to ask
the user to input the answer three times and break the loop if the answer is correct.
The result of the program was that the user was able to access their information by
verifying their authenticity.
CONTINUE
Sample:
1. Create a program that will take input (string type) from the user such as the item
category, item name, and quantity, and calculate the total amount of items
purchased. Each items must have the corresponding letter to be chosen by the
user.The program should also allow the user to continue buying items until they
choose to exit. The following items are available to be purchased:
The problem is to give users chance to choose their wants and calculate the total
amount of the items the user wants to purchase. It is important as it helps the user
to calculate and pay the total amount while they shop in the supermarket. The
methodology used in this code was to create a dictionary for the items and prices
and then use a while loop for the user to buy items, and a continue statement so
that the user will have the chance to continually choose items. During the process
no extra parameters are used. The result showed that the code was able to
calculate the total amount of items chosen by the user.
2. Write a program that take input from the user and check if a number is deficient or
not. A number is said to be deficient if the sum of its proper divisors is less than
twice that number.
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
46
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
The problem is to determine whether the given input (integer type) is a deficient
number of not. In order to solve this problem, I have used a divisor of the given
number and identified it as a deficient if the sum of the divisors is lesser than the
number and also an If-elif condition is used in the program and an extra parameter
identified as a list ‘new’ and integer ‘total’ is used. Hence, the output show that the
number is either deficient or not, depending on the condition that is satisfied.
PASS
Sample:
1. Write a program that remove the same items that exist in each list, given the list are
list_1 with the values of 1, 7, 3, 8, 5, and list_2 with the values of 2, 3, 9, 5, 6.
The problem was to create two new lists which contain items that are not present in
both the lists. I solved the problem by iterating through each list and checking if the
item exists in both the lists. If it does not exist, then I added it to the new lists. Yes,
this product can be used as an independent program. I used the iterative approach
to solve this problem as it was the most efficient way to find the unique items in both
the lists. The output were two new lists with unique items from each list. From the
results, we can conclude that the iterative approach was successful in finding the
unique items from both the lists.
2. Write a program to allow the user to guess a random number in list from 1 to 9, the
program must take input from the user (integer type). The user is given 3 chances
to guess the correct number and the program will display the result if the user
guesses the correct number or not.
The problem is to match the input numbers of the user from the random generated
number of the program. We used a ‘random’ module that provides a random output
from the given range of values. The product can be used as an independent
program as the program has been tested and is working fine. And we concluded
that the program is successful in generating a random number and allowing the
user to guess it in a limited number of attempts.
Code:
WHILE LOOP
Traffic Light
import time
time.sleep(5)
colour = 'red'
else:
print('RED light is on. Countdown begins in 5 seconds...')
time.sleep(5)
colour = 'green'
Disarium or Not!
# While loop
# Define a function that will count the digits present in a number
def calculateLength(n):
length = 0;
while (n != 0):
length = length + 1;
n = n // 10;
return length;
BREAK
Test your Skill!
import random
import time
print('You have 5 seconds to answer each question')
print('Type \'x\' to Exit the Game')
correct_answers = 0
# Runs forever
while True:
# generate two random numbers
num1 = random.randint(5, 20)
num2 = random.randint(5, 20)
# check if time is up
elapsed_time = time.time() - start_time
if elapsed_time > 5:
print("Time's up! Game Over")
print("Time taken {:.2f}".format(time.time() - start_time),'seconds')
break
Authentication Test
a1 = 'Infantes'
a2 = '98'
a3 = '2425'
count = 0
print('To access your information you must pass the three authentication test')
else:
print("Incorrect!. Please try again.")
count += 1
CONTINUE
SuperMart
total = 0
# if not in the choices it will go back to start and ask category from the user again
if item_name not in ['A', 'B', 'C', 'D']:
print("Sorry, that is not a valid selection. Please try again.\n")
continue
# if user does not want to buy anything, print the total and exit
if buy_again not in ["y", "Y"]:
print("\nThank you for your purchase.\nTotal Amount: Php",
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
51
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
"{:.2f}".format(total))
break
Deficient Numbers
# Initialize a variables
total = 0
new = []
n = int(input("Enter a number: ")) # prompt the user to enter an input
for divisors in range(1, n+1): # loop used to find the divisors of n
if n%divisors == 0:
new.append(divisors)
continue
print("List of divisors: ",new) # the sum of the list is printed
for x in range(0, len(new)): # loop used to sum the list of divisors
total = total + new[x]
PASS
Set of Intersection
list_1 = [1, 7, 3, 8, 5]
list_2 = [2, 3, 9, 5, 6]
for j in list_2:
# check if item exists in both lists
if j in list_1:
# If it does, pass it and do nothing
pass
# If it does not exist in the first list, add it to the new list_4
else:
list_4.append(j)
import random
else:
print('Better Luck Next Time!!')
print("The Number is", correct_guess)
WHILE LOOP
Traffic Light
Based on the code, the goal was to simulate a traffic light and count down 10 seconds
when each colour is on. The hypothesis was that the code would run with no errors, and
upon running the code, this was proven to be true. The code began by initializing the
traffic light to green and then began a loop. Within the loop, the code ran for each colour
and then reset the colour to the next colour in the sequence. The results showed that
the program ran successfully, printing the correct message and counting down for 10
seconds for each colour. Hence, the problem was solved and simulated effectively
under the specified conditions. If a different method or equipment was employed, the
results would likely remain the same. However, the code may vary depending on the
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
53
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
language or framework utilized. The results are in accordance with the general theory of
the question, as the traffic light was simulated effectively under the specified conditions.
Disarium or Not
The goal of this code was to determine whether a number is a disarium number or not.
My hypothesis was that the code would correctly identify any given number as a
disarium number or not. Step by step, the code first defined a function called
calculateLength which would count the digits present in a number. Then it accepted an
input number from the user. It then made a copy of the original number and calculated
the sum of the digits powered with their respective position in the number. Finally, it
checked whether the sum was equal to the number itself and prints the appropriate
output. The results of this code were as expected. It correctly identified the given
number as a disarium number or not. Using different method or equipment might
resulted in inaccurate output.
BREAK
Test your Skill!
This code is used to create a game where the user has to answer simple math
questions within 5 seconds. The code first imports the random and time modules. Then
it prints an instruction to the user. After that, a variable "correct_answers" is initialized to
store the score of the user. Then a while loop is used to generate two random numbers
from 5 to 20 and calculate their sum. The user is then asked to enter the answer which
is then stored in the variable "user_answer". If the user enters "x" then the game is
exited. If the time is up, the game is also exited. If the user enters the correct answer,
then the score is incremented by one and the time taken to answer is printed. Finally, if
the user enters the wrong answer, the game is exited and the score is printed. If other
methods or equipment were used, the results would be different depending on the
method or equipment. For example, if a different timer were used, then the user would
have a different time limit to answer the questions. In conclusion, the results of this code
show that the game works as intended, and the user is able to answer the questions
within the allotted time.
Authentication Test
The code is about authentication test that requires user to answer three questions. My
hypothesis was that the code would be able to successfully authenticate the user if the
answers to the three questions were correct. The code begins by declaring three
variables, a1, a2, and a3, which are the answers to the three questions. The code then
prints a statement to the user informing them they must pass a three-authentication test.
The code then begins a loop that will run three times, allowing the user to input an
answer each time. The first question requires the user to provide their mother's maiden
name, and if the answer is correct, the loop moves to the second question. The second
question requires the user to provide their favorite number, and if the answer is correct,
the loop moves to the third question. The third question requires the user to provide the
last four digits of their Visa card, and if the answer is correct, the loop ends and the user
is granted access its classified information. However, if any of the answers are
incorrect, the loop will require the user to answer the questions again. If the user has
two incorrect answers, the loop will end and the user will be informed they have
exceeded the maximum attempts and will output a feedback to try again after 24 hours.
If other method will be used the result might be different depending on the required
questions. Finally the program was able to provide security for the confidential file.
CONTINUE
SuperMart
The program is focused on giving customers more easier way to shop. Through the
code, the user is able to select from four categories (Fruit, Vegetables, Condiments, and
Spices) and enter the letter of the item they would like to purchase as well as the
quantity. The program then calculates the total cost of all the items purchased and
prints it for the user. My hypothesis of the program being able to successfully calculate
the total cost of items was true. Step by step, the program first welcomed the user and
started a while loop for them to buy items. It then printed the categories and items, with
their corresponding prices, that the user could choose from. The user then had to input
the category they would like to shop in and the letter of the item they would like to
purchase. After that, the user had to enter the quantity of the item they would like to
purchase. The program then calculated the total cost of the items and asked the user if
they would like to buy anything else. If they chose no, the total cost of all the items was
printed and the program exited. If they chose yes, the loop would continue. If any of the
user's inputs were invalid, the program would start from the category selection again. If I
used other methods or equipment, the program may have been more efficient, but it
would have taken more time and effort to code. The results of this program correlate
with the general theory that a user should be able to shop in a supermarket and
calculate the total cost of their items.
Deficient Number
In this code, the goal was to determine if a given number is deficient or not. My
hypothesis was that the number would be deficient if the sum of its divisors is less than
twice the number. After running the code, my hypothesis was proven true. The code first
took the input of a number, then it found all the divisors of the number and stored them
in a list. Then it calculated the sum of the list and compared it to twice the number. If the
sum was less than twice the number, it will print that the number is deficient; otherwise,
the number is not deficient. If another method or equipment were used, it is possible
that the results may vary. However, these results follow the general theory of this
question, which is why the hypothesis was proven true.
PASS
Set of Intersection
Based on the problem, the code was focused on comparing two lists, list_1 and list_2,
and create two new lists which are list_3 and list_4 with the unique values from each.
The goal of this code was to create two new lists from two existing lists, list_1 and list_2,
by adding the values which did not exist in either of the lists. The program followed a
step-by-step process to achieve this goal. The first step was to create two empty lists,
list_3 and list_4, which would store the values from the existing two lists. Then the
program iterated through each list, where it checked if the items in list_1 existed in list_2
and vice versa. If the item did not exist in either of the lists, it was added to the
respective new list. Finally, the program outputted the new values of each list. The
results of this code show that the program successfully created two new lists, list_3 and
list_4, containing the values which were not common between list_1 and list_2. If a
different method or different equipment were used, the results might be different.
However, the general theory of the problem remained the same.
The code begins by printing a random value from a list of numbers 1-9. Then, it sets up
a guess count, guess limit, and prints a message for the user to enter a number
between 1-9, with a limit of 3 chances. A while loop is used to check if the guess is
correct, and if it is, the user has won. If not, the loop continues until the user has used
up all 3 chances. If the user has used all 3 chances, then the program prints a message
letting them know they have lost, and the number that was chosen. The goal was to
guess the correct number in the range of 1-9, and if the hypothesis was correct, then
the user would win. The results indicate that if the user guessed the correct number,
they won; if not, they lost. If another method or equipment was used, the results may
differ, or the same. The results correlate with the general theory that the user must
guess the correct number with 3 chances in the range of 1-9 in order to win.
References:
Python while loop: 5 examples with break, continue, and else clause (jquery-az.com).
Retrieved from https://www.jquery-az.com/python-while-loop-5-examples-with-
break-continue-and-else-clause/
LABORATORY REPORT
No. 10
Linear Search Algorithm
Objectives:
Abstract:
Sample:
1. Suppose that a list contains 20 values from given range of numbers 1-99 without
any duplicates. The program must take input from the user entering the chosen
number from the given list returning the index of the input and calculating the rank in
decile value.
The problem is to calculate the rank value of the given input (integer type) chosen
from the outputted random list of numbers. The program outputs the list of random
generated numbers, index of the number, and calculated in decile value of the input
using the O(n) Big-Oh Notation. During the processing or calculation phase an extra
parameter identified as are; ‘se’ (set type) and ‘lst’ (list type), is used to remove the
duplicates and sort the list of numbers in ascending order. Hence, the decile value
is calculated by dividing the rank of observation to total number of observations and
multiplying it to 10. Therefore, the mathematical formula is:
Dk = ( Kn )∗10
2. Write a program that prompt user to choose from the value of A-E with the
corresponding value of index from 0-4. The list must contains "Jackpot", "Better luck
next time", "It is what it is", "It ain't over", and "Life goes on" to be shuffled each run.
The problem was to create a program that could randomly select an item from a list
and then check if that item is the one the user wanted. The program was developed
using the linear search methodology for searching for the 'Jackpot' string within the
list. The output of the program is that it successfully prints the string associated with
the user's input and if the string is 'Jackpot', it prints the index of the 'Jackpot' string
within the list. In conclusion, this program provides a way for users to play a game
of chance that requires a random element, and it can be used as an independent
program.
Code:
Decile
import random
from random import randint
from natural import number
lst = []
# Generates random numbers up to 20
for i in range(21):
value = randint(1, 99)
new = lst.append(value)
else:
print("ERROR: Chosen Number is not in the list!")
Hitting D Jackpot
import random
#cList of strings
choices = ["Jackpot", "Better luck nextime", "It is what it is", "It ain't over", "Life
goes on"]
win = "Jackpot"
Decile
The program is focused on calculation of the rank of observation of the given input from
a list of random numbers using the formula of decile. The program first creates an
empty list named ‘lst’ and generates list of random numbers up to 20 using the randint
function from range of 1 to 99. Then, it removes the duplicate sample and sorts the list
using the set and random functions. Next, it prints the generated random numbers and
creates the LinearSearch function to check if the value is in the list. After that, it prompts
the user to choose a number and check if it is in the list, if it is in the list it will print the
corresponding index of the chosen number or else it will provide a feedback error that
the input is not in the list. Finally, it creates the decile_value function to calculate the
rank of decile value of the input and output the result. Hence, the results showed that
the chosen number is at the xth decile, where x is the index of the chosen number in the
list, and calculation process.
Hitting D Jackpot
By running the code, the user can play a game of chance to choose a box from A-E.
The code first creates a list of strings, which is randomly shuffled. Then, the user is
prompted to choose a letter from A-E. If the user input is not in the choices, an error will
be outputted, and the program will exit. Otherwise, the code uses an if-elif statement to
assign a string to the user input's with the corresponding index in the list. After that, the
code uses a linear search algorithm to check if the string associated with the user input
is "Jackpot". If it is, “congratulations” is printed. Otherwise, the index of "Jackpot" within
the choices list is printed. Finally, the code prints the string associated with the user
input. My goal was to check if the user input will hit the "Jackpot", and my hypothesis
was true. The results were that the string associated with the user input was printed,
and the index of "Jackpot" within the list was also printed. And If I used another method
or equipment, the results might be different. For example, if the list was sorted instead
of shuffled, the index of "Jackpot" within the list might have been different.
From this lab I learned that linear search algorithm is an efficient way to search
for a specific item in a list. Linear search algorithms are designed to look through a list
of items by comparing each item to the item being searched for until the item is found.
This method can be used to find a specific item in a list of items, such as searching for a
specific number in a list of numbers. The linear search algorithm is a simple yet effective
way to search for a specific item in a list. Moreover, it can be used as an independent
program and can be implemented in Python using object-oriented programming
principles.
References:
FreeCodeCamp (2020, April 27). Search Algorithms: Linear and Binary Search
Explained. Retrieved from https://www.freecodecamp.org/news/search-
algorithms-linear-and-binary-search-explained/
LABORATORY REPORT
No. 11
Binary Search Algorithm
Objectives:
Abstract:
The Binary Search Algorithm is an efficient method for finding an element in a sorted
array. Python provides a built-in function that can be used to perform binary search on a
list. The algorithm works by repeatedly dividing the search interval in half and
determining which half of the array contains the target element. The search begins by
comparing the middle element of the array with the target value. If the target value is
less than the middle element, the search continues in the lower half of the array. If the
target value is greater than the middle element, the search continues in the upper half of
the array. The process is repeated until the target value is found or the search interval is
empty. The time complexity of the Binary Search Algorithm is O(log n), making it more
efficient than linear search algorithms for large arrays. Here are some basic applications
of binary search algorithm.
Sample:
1. Given a sorted list of numbers 2, 4, 5, 6, 7, 8. Write a program that adds a new
element in a given list. The given element is 3 that should be added in its right
position. The program should output the new list and the index at where the new
element is added.
The problem was to determine the index at which an element should be inserted in
an array in order to maintain the order of the elements. The program used binary
search algorithm to find the index at which the element should be inserted. This
product can be used as an independent program as it is a standalone function that
can be used to search and insert elements into an array. It was used because it is
an efficient method for searching through sorted data. The results successfully
showed the desired output.
2. Suppose that a list contains the values 20, 44, 48, 55, 62, 66, 74, 88, 93, 99 at
index positions 0 through 9. Trace the values of the variables left, right, and
midpoint in a binary search of this list for the target value 90.
This code is performing a binary search to find the index of a target value in a given
list. The list is initially created with size of 10 and the target value is set to 90. Left
and right variables are initialized to 0 and the size of the list respectively. Then a
while loop is used to iterate through the list to find the index of the target element. If
the element is found, its index is printed, otherwise the message 'Element is not
present' is printed.
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
62
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
Code:
Code 1
# Keep searching until the start index is greater than the end index
while start <= end:
mid = (start + end) // 2 # calculate the midpoint of the search range
# If the loop ends without returning, the target must not exist in the array
# Insert the element at the start index
arr.insert(start, target)
return start # return the start index
Code 2
# Creating a list
list_1 = [20, 44, 48, 55, 62, 66, 74, 88, 93, 99]
left = 0
right = len(list_1)-1
Code 1
The code is focused on adding a new element to the sorted list. The binary search was
conducted to add the new element. This resulted in the new array being 2, 3, 4, 5, 6, 7,
8. The target element was found and the index returned was 1. The program worked by
creating a while loop, where in it will find the middle element of the list, and then the
program will then compare the given value by going through each indices starting right
to left. If the given element if found to be lesser it will start to search in lower value of the
list which is in the left corner. Finally, the program will then print the new list with the
given value in its right position and at what index it’s in. My hypothesis was confirmed
which was that the binary search will find the element and return its index in the array.
And the goal of the code was achieved. If I used a different method or equipment, the
output would differ. For example, I could have used a linear search which would have
taken a longer time to find the target element in the array. The results correlate with the
general theory of the question as the binary search algorithm is efficient for finding
elements in an array. It has a time complexity of O(log n) which is more efficient than
linear search which has a time complexity of O(n).
Code 2
The goal of this code was to find the index of a given target value in a given list of
integers. The program started with creating a list, followed by assigning a target value.
Then, the left and right index were initialized. After that, the code entered the binary
search loop. In the loop, it will find the midpoint of the list and check if it was equal to the
target value. If it was, the index of the element was then printed, and the loop will stop.
If it is not, the left or right index will be adjusted according to the comparison. Finally, if
the element is not present, the code will print a message saying that the element is not
found. Hence, the results showed that the element is not in the list.
References:
FreeCodeCamp (2020, April 27). Search Algorithms: Linear and Binary Search
Explained. Retrieved from https://www.freecodecamp.org/news/search-
algorithms-linear-and-binary-search-explained/
LABORATORY REPORT
No. 12
Stacks
Objectives:
To Understand the concept of stacks and how they are implemented in Python
Familiarize with common stack algorithms such as push, pop, and peek in
Python.
Abstract:
A stack is a fundamental data structure in computer science that follows the Last-In-
First-Out (LIFO) principle. In Python, stacks can be implemented using built-in data
structures such as lists and LifoQueue, and common stack algorithms such as push,
pop, and peek can be applied. This abstract provides an overview of the concepts and
implementation of stacks in Python, including the use of common stack algorithms.
Sample:
1. You have been asked to create a text editor application that allows users to input
text, undo and redo their actions, and clear the entire document. The application
should keep track of the user's actions and allow them to undo and redo their
actions as needed. The user should also be able to clear the entire document if they
wish. Write a program that allows the user to input text and perform these actions in
the text editor.
The code is designed to create a text editor that allows users to input text, undo and
redo their actions and clear the entire document. It addresses the common problem
of making mistakes while editing text and wanting to undo or redo an action, as well
as the need to clear the entire document. The program uses a unique approach in
its implementation, utilizing two separate stacks for undo and redo functionality, and
implements object-oriented programming to organize the different functions and
variables of the text editor. The end goal is to deliver a functional text editor that can
meet the user's needs in terms of editing text efficiently and effectively.
2. A snack shop manager wants to keep track of the available snacks using a stack
data structure. They need to create a class called "Stack" that can store the names
of the snacks. The manager wants to be able to add new snacks to the stack when
they arrive, remove them from the stack when they are sold out, and check the top
snack in the stack without removing it. They also want to be able to check the size
of the stack, check if the stack is empty, and display the list of snacks in the stack to
manage the stock of the snack shop. They need a code that can help them
implement these functionalities in the stack.
The problem addressed in this code is to create a program that can effectively manage
a stack of items, such as those found in a snack shop. The stack data structure is a
suitable choice for this problem as it allows for easy insertion and removal of items in a
Last-In-First-Out (LIFO) order, which is the most efficient way to keep track of the
available items in a snack shop. The program is built on a Stack class that includes
methods for inserting new items, removing items, checking the top item, checking the
size of the stack, and checking if the stack is empty. The main function creates a stack
object and provides a user-friendly menu-based interface for interacting with the stack
and performing the aforementioned operations. This program can be used as an
independent tool for managing the inventory of a snack shop and keeping track of the
available items at all times.
Code:
Based Text Editor
class TextEditor:
def __init__(self):
# Initialize two stacks for undo and redo, and a string for text
self.undo_stack = []
self.redo_stack = []
self.text = ""
def undo(self):
# If there is text to undo, add current text to redo stack
# and set text to previous text in undo stack
if not self.undo_stack:
return
self.redo_stack.append(self.text)
self.text = self.undo_stack.pop()
def redo(self):
# If there is text to redo, add current text to undo stack
# and set text to previous text in redo stack
if not self.redo_stack:
return
self.undo_stack.append(self.text)
self.text
def clear(self):
# Save current text to undo stack and clear text and redo stack
self.undo_stack.append(self.text)
self.text = ""
self.redo_stack.clear()
Stack Organizer
class Stack:
def __init__(self):
self.items = [] # Initialize an empty list to store stack items
def pop(self):
"""Pop an item from the top of the stack.
def peek(self):
"""Return the top item of the stack without removing it.
def size(self):
"""Return the number of items in the stack."""
return len(self.items)
def is_empty(self):
"""Return True if the stack is empty, False otherwise."""
return self.items == []
def main():
stack = Stack() # Create a stack object
while True: # Loop that allows user to enter input infinite times
print("\nEnter 1 to push an element to the stack")
print("Enter 2 to pop an element from the stack")
print("Enter 3 to peek at the top element of the stack")
print("Enter 4 to get the size of the stack")
print("Enter 5 to check if the stack is empty")
print("Enter 6 to display the list of inputs")
print("Enter 0 to exit")
if __name__ == "__main__":
main()
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
69
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
The code is implemented in the form of a Stack class that includes methods for inserting
new items, removing items, checking the top item, checking the size of the stack, and
checking if the stack is empty. The main function creates a stack object and provides a
user-friendly menu-based interface for interacting with the stack and performing the
aforementioned operations.
The code first defines the TextEditor class, which includes the init method that initializes
two stacks for undo and redo and a string for text.
def __init__(self):
self.undo_stack = []
self.redo_stack = []
self.text = ""
The input method is used to save the jcurrent text to the undo stack, adds new text to
the document, and clears the redo stack because new input invalidates previous redos.
The undo method is used to undo the last action, it checks if there is text to undo, add
current text to redo stack, and set text to previous text in undo stack.
def undo(self):
if not self.undo_stack:
return
self.redo_stack.append(self.text)
self.text = self.undo_stack.pop()
The redo method is used to redo the last action, it checks if there is text to redo, add
current text to undo stack, and set text to previous text in redo stack.
def redo(self):
if not self.redo_stack:
return
self.undo_stack.append(self.text)
self.text
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
70
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
The clear method is used to clear the current text, it saves the current text to undo stack
and clears the text and redo stack.
def clear(self):
self.undo_stack.append(self.text)
self.text = ""
self.redo_stack.clear()
In the main function, a TextEditor object is created, and a while loop is entered that
allows the user to enter input infinite times. The user is provided with a menu of options,
such as undo previous inputs, redo previous undo actions, clear the current text and exit
the program. Depending on the user's choice, the corresponding method is called on
the TextEditor object.
The results of this program show that it effectively manages a stack of items, providing
a user-friendly interface for inserting, removing, and checking the items in the stack.
The code uses appropriate data structures and operations to handle the stack and its
elements. If we were to use a different data structure, such as a queue, the program
would not be as efficient in managing the stack of items, as the LIFO property of a stack
is crucial for this use case. The results of this program align with the general theory and
principles of stack data structures, and the code effectively uses the appropriate
variables and functions to achieve the desired outcome.
Stack Organizer
The goal of this code is to create a Stack class that implements the basic operations of
a stack, such as push, pop, peek, size, and is_empty. The hypothesis is that this code
will successfully create a stack object and allow the user to perform these operations on
it through a user-friendly interface.
The code first defines the Stack class, which includes the init method that initializes an
empty list to store the stack items. This method is called when a new stack object is
created and creates an empty list that will hold the items in the stack.
In the push method, an item is passed as an argument and is added to the stack by
appending it to the items list. This method also prints a message to confirm that the item
has been pushed to the stack.
In the pop method, the last item of the list is removed and returned. If the stack is empty
an error message is printed.
def pop(self):
if self.items:
popped_item = self.items.pop()
print(f"{popped_item} popped from stack")
return popped_item
else:
print("Stack is empty")
The peek method returns the last item of the list without removing it. if the stack is
empty, an error message is printed.
def peek(self):
if self.items:
return self.items[-1]
else:
print("Stack is empty")
The size method returns the length of the items list, which represents the number of
items in the stack.
def size(self):
return len(self.items)
The is_empty method returns a Boolean value that indicates whether the stack is empty
or not.
def is_empty(self):
return self.items == []
In the main function, a stack object is created and a while loop is entered that allows the
user to enter input infinite times. The user is provided with a menu of options, such as
pushing an element to the stack, popping an element from the stack, peeking at the top
element of the stack, getting the size of the stack, checking if the stack is empty, and
displaying the list of inputs. Depending on the user's choice, the corresponding method
is called on the stack object.
Overall, the code line by line, implements the basic operations of a stack and provides a
user-friendly interface to interact with the stack.
References:
Stack in Python (n.d.). Retrieved from https://www.geeksforgeeks.org/stack-in-python/
Stack in Python (Javatpoint, n.d.). Retrieved from https://www.javatpoint.com/stack-in-
python
LABORATORY REPORT
No. 13
Queues and Dequeues
Objectives:
To apply the various methods and use such as FIFO and LIFO algorithm of
Queues and Dequeues in Python programming.
Understand the differences between queues and dequeues in terms of their
structure, operations, and usage, and be able to identify when to use each data
structure in various real-world scenarios.
Abstract:
QUEUES
Queues are like arrays, but you can only add nodes to the tail node, which is called the
rear node, and remove nodes from the head node, which is called the front node. In
linked lists, you’re quite free to access, insert, delete, and change any node in the list
however you please, and at any time. But in a queue, once a node is added, or
enqueued, you won’t have anyway of accessing it until it reaches the front of the queue
and is removed, or dequeued. Queues will often be described as having a first in, first
out (FIFO) structure, meaning the oldest node in the queue is the one you’ll have access
to. Queues will be structured quite similarly to linked lists, and have a front, rear, and
size attributes, but they will not have an index or a way to look inside the middle of the
queue. Alongside that same limit, the front and rear nodes are only used to dequeue and
enqueue nodes.
Sample:
1. Write a program to simulate contact numbers entered by the user. The program must
take 11 digits from the user starting with ‘09’, then be modified into Philippine Country
Code format ‘+63’. The program must also have options where the contact numbers
can be viewed or be removed and allows the user to exit.
The problem is to modify phone numbers to ensure the numbers are properly
formatted with a “+63” prefix and no leading zeroes showing the country code. The
solution uses a Queue class, which is initialized with a maximum size of 11 and is
used to enqueue and dequeue the digits of the phone number. The modified phone
number is then added to a list of contact numbers. The program also includes
functionality for viewing, clearing, and exiting the program. The code can be used as
an independent program, as it includes a main() function that runs the program's
functionality. The methodology used is enqueueing and dequeueing of digits in a
queue to format phone numbers. The results of the program are a list of properly
formatted phone numbers.
2. Write a program that simulate the queue of customers that come to the bank. The
program should allow the user to use the following options to add, remove, display
the removed customer, and print the current queue. The program must also display
the input with the corresponding date and time joined, the same thing will be done
when a customer is removed from the queue.
The problem is to keep track of the customers in the bank. The program utilizes a
Queue class to keep track of customers that are added and removed from the queue,
as well as maintaining a record of removed customers and their corresponding arrival
time. The concept of this program demonstrates how queues are being applied in a
real-world scenario and this can be used as an independent program as it includes
the necessary functionality in the main function. Hence, the result effectively
manages the queue of customers and keep a record of removed customers through
the use of Queue data structure.
DEQUEUES
Deques (pronounced like “decks”) are like arrays, but a more apt comparison would be
that they’re like a combination of queues and stacks. Deque is supposed to be an
abbreviation of “Double-Ended Queue”, which looks odd, but it helps differentiate it from
the “dequeue” method that queues have. What makes deques special is that nodes can
be added and removed from both the head and tail, or since neither end is more
important than the other, the left and right nodes (front and rear are sometimes used,
too). Because the nodes aren’t necessarily moving in either direction, and can be added
and removed from each end, stack’s pop and push are the terms used for insertions and
deletions.
Sample:
1. Write a program the keep tracks of its inventory, shipments and zip code. The
program should allow user to add new item to the warehouse and ship the items
chosen by the user given that information such as where the item will be shipped,
and the location’s zip code must be taken from the user. The output must display the
item, location with its zip code and a generated 5-digit tracking number.
The problem is to make a more efficient and organized way of tracking inventory and
simplifies the process of shipping items, allowing user to add new items to the
warehouse and ship them. By using the dequeue data structure and the random
module the problem of tracking inventory, shipments and zip codes was solved. The
product can be used as an independent program as it has the necessaries functions
that can be used in real life scenarios. The methodology used was to create a
Warehouse class which uses the deque data structure to store and remove items.
The results showed that the program works as expected, generating the 5-digit
tracking numbers and displaying the item, location and zip code when a shipment is
made. Overall, this program is a great way to organize and track shipments and
inventory.
2. A generated list of letters is given in a random order, the user must arrange these
letters following the given random format of the program. The program must allow
user to move pieces to front to back of the list and check if the puzzle is complete.
The program must display the moves made and the time taken to complete the
puzzle.
The problem is to arrange the random generated list of letters in its format. This
concept is important as it helps the user to arrange the ordered list of letters by just
moving the letters to both sides. Also, this demonstrate how dequeues are used. The
methodology used is a dequeue from collections and the random module to shuffle
the puzzle pieces. Furthermore, this product can be used as an independent
program as it provides the user with the flexibility to move the pieces to the front and
back of the list. The results of the program demonstrate that the puzzle was
completed in the given time frame and the list of moves made by the user. Thus, the
program is a success.
Code:
QUEUES
Contact Data Base
class QueueFullError(Exception):
pass
class QueueEmptyError(Exception):
pass
def main():
# A list to store the modified phone numbers
contact_numbers = []
print('Option:\nv = to view\nc = to clear\nx = exit')
while True:
# Read the input number
number = input("Enter an 11-digit number starting with '09': ")
if number == "v":
# Print the list of contact numbers
print("Contact numbers:")
for number in contact_numbers:
print(number)
elif number == "c":
# Clear the list of contact numbers
contact_numbers.clear()
print("Contact numbers cleared.")
elif number == "x":
# Exit the program
break
else:stomer
# Check if the number is an 11-digit number starting with '09'
if not number.startswith("09"):
print("Invalid input. Please enter an 11-digit number starting with '09'.")
continue
# Dequeue the digits from the queue and build the modified number
modified_number = "+63"
while not q.is_empty():
digit = q.get()
if digit != "0":
modified_number += digit
if __name__ == "__main__":
main()
class Customer:
def __init__(self, name, arrival_time):
# Initialize the Customer instance with a name and arrival time
self.name = name
self.arrival_time = arrival_time
class Queue:
def __init__(self):
# Initialize the Queue instance with an empty queue and a list of removed customers
self.queue = []
self.removed = []
def remove(self):
# Remove the first customer from the queue and print a message
customer = self.queue.pop(0)
removal_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.removed.append((customer, removal_time))
print(f'{customer.name} has left the queue at time {removal_time}.')
return customer
def print_queue(self):
# Print the queue
print('Queue:')
for customer in self.queue:
print(f' {customer.name} (arrived at time {customer.arrival_time})')
def print_removed(self):
# Print the removed customers
print('Removed Customers:')
for customer, removal_time in self.removed:
print(f' {customer.name}(removed at time {removal_time})')
# Create a queue
q = Queue()
# Continuously prompt the user for input until they choose to quit
while True:
# Get the user's choice
choice = input('Enter your choice: ')
if choice == '1':
# Add a customer to the queue
name = input('Enter the customer name: ')
arrival_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
q.add(Customer(name, arrival_time))
elif choice == '2':
# Remove a customer from the queue
q.remove()
elif choice == '3':
# Print the queue
q.print_queue()
elif choice == '4':
# Print the removed customers
q.print_removed()
elif choice == '5':
# Quit the program
break
else:
print('Invalid choice!')
DEQUEUES
Warehouse
import random
from collections import deque
class Warehouse:
def __init__(self):
# Initialize an empty deque for the items
self.items = deque()
# Initialize an empty deque for the tracking numbers
self.tracking_numbers = deque()
# Initialize an empty deque for the zip codes
self.zip_codes = deque()
self.items.remove(item)
#self.zip_codes.popleft()
def generate_tracking_number(self):
# Generate a random tracking number
tracking_number = random.randint(10000, 99999)
# Check if the tracking number has already been used
if tracking_number in self.tracking_numbers:
# Generate a new tracking number if the current one has already been used
tracking_number = self.generate_tracking_number()
return tracking_number
def check_inventory(self):
# Return a list of the items in the deque
return list(self.items)
while True:
# Prompt the user to choose an action
action = input("Enter 'r' to receive a shipment, 's' to ship an item, or 'q' to quit: ")
if action =='q':
break
elif action == 'r':
# Prompt the user to enter the item to receive
item = input("Enter the item to receive: ")
# Receive the shipment
warehouse.receive_shipment(item)
elif action=='s':
# Prompt the user to enter the item to ship
item = input("Enter the item to ship: ")
# Prompt the user to enter the destination
destination = input("Enter the destination: ")
# Prompt the user to enter the zip code
zip_code = input("Enter the zip code: ")
else:
# Print an error message if the input is invalid
print("Invalid input. Please try again.")
Jigsaw Puzzle
import time
from collections import deque
import random
new = pieces
random.shuffle(new)
The given code is a simulation of a customer queue management system. The program
starts by creating a class called 'Customer' which includes the customer's name and
arrival time as attributes. Another class called 'Queue' is also created, which includes a
queue of customers, and a list of removed customers. The class includes several
methods such as 'add' which adds a customer to the queue and prints a message,
'remove' which removes the first customer from the queue and prints a message,
'print_queue' which prints the current queue, and 'print_removed' which prints the list of
removed customers. The program then prompts the user for input on which action to
take, such as adding or removing a customer from the queue, or printing the current
queue or removed customers. Overall, the code successfully demonstrates the
implementation of classes and methods in Python, and the goal of simulating a
customer queue management system is achieved. The hypothesis that classes and
methods can be used to create a customer queue management system simulation is
true. The results are displayed step by step as the user interacts with the program, and
the code is easy to follow and understand. The use of the datetime library allows for the
accurate tracking of customer arrival and removal times. If other methods were used,
such as using lists instead of classes, the program would not have the same level of
organization and structure. The results of this program are in line with general queue
management systems and the use of classes and methods in Python programming.
DEQUEUES
Warehouse
Based on the problem the code is designed to manage a warehouse, allowing the user
to enter shipments, zip codes, and ship an items. The code begins by importing the
random and deque modules from the collections library. Next, the code defines a
Warehouse class and initializes it with 3 empty deques for items, tracking numbers and
zip codes. The code then includes a receive_shipment() method, item_zipcode()
method, and a ship_item() method that allows the user to generate a random tracking
number for the shipped item. Additionally, the code includes a check_inventory()
method that returns a list of items in the deque. After instantiating a new warehouse, a
loop is created that allows the user to choose from 3 different actions: receive a
shipment, ship an item, or quit. The goal of the code is to manage a warehouse and it
was achieved. The hypothesis was true. The code was able to receive shipments, zip
codes, and ship items with a randomly generated tracking number. If a different method
or equipment was used, it would not be as efficient as the code written here. The results
are in line with the general theory of this question.
Jigsaw Puzzle
This code was written to solve a jigsaw puzzle. The program starts by initializing the
deque of puzzle pieces and shuffling it. Then, the list of moves is initialized and the
timer is started. The main menu is then printed and the main program loop is started.
The user is presented with choices/options to move a piece to the front or back of the
deque, check completion or to quit. When the user moves a piece to the front or back,
the program removes the piece from the deque and adds it to the front or back. It also
adds the move to the list of moves. The program then checks to see if the puzzle is
complete and, if so, it stops the timer and calculates the elapsed time. The results show
that the goal of completing the jigsaw puzzle was achieved. The hypothesis that the
code would work was true. If other methods or equipment were used, the result may
have been different since the deque and random functions are unique to this code. The
results of the code correlate with the general theory in terms of the goal of completing
the jigsaw puzzle.
References:
Matthes, K. (2020). Abstract Data Types: Queues, Stacks, and Deques. Medium.
https://medium.com/@karlmatthes/abstract-data-types-queues-stacks-and-
deques-cbc8e8d360c9
LABORATORY REPORT
No. 14
Preorder Traversal, Inorder traversal
and Postorder traversal
Objectives:
To understand the underlying concepts and principles of preorder, inorder, and
postorder traversal algorithms.
To develop the skills to implement preorder, inorder, and postorder traversal
algorithms on a binary tree data structure using Python programming.
Acquire knowledge of the traversal order and process of each algorithm,
including their unique characteristics and complexities.
Abstract:
PREORDER TRAVERSAL
Sample:
1. Write a program that keep track of its employee performance evaluations, the
structure of the program must be in binary tree data where each employee is
represented by a node with their name and performance rating. The program must
display the employee’s name with their corresponding average evaluation in
preorder form.
The problem was to create a binary tree data structure to represent each employee
and their corresponding performance rating, and to display the employee's name
and average evaluation in preorder form. This concept is important because it
addresses the problem of keeping track of employee performance evaluations in an
efficient and organized way. The problem was solved by creating a class called
Employee to represent each individual employee and their performance rating, and
then defining a preorder traversal function to print the employee's name and
performance rating in preorder form. This program can be used as an independent
program to keep track of employee performance evaluations. The methodology
used in this program was a binary tree data structure and preorder traversal. The
results of this program are a data structure and a preorder traversal function that
can be used to keep track of employee performance evaluations in an efficient and
organized way.
2. Write a program based on a binary tree which contain 7 nodes, each node must
contain a random generated number from 1 to 20. The program must prompt user
to change the value of the specific node and displays it in preorder traversal.
This code creates a binary tree with 7 nodes, each containing a random number
from 1 to 20. The user is prompted to change the value of a specific node (integer
type), and the tree is displayed in preorder traversal after the update. The use of
binary tree data structure is important as it allows for efficient organization and
manipulation of large data sets. The problem was to create a program that allows
for the updating of a specific node in the tree. The program solved this problem by
using a preorder traversal function to display the tree and an ‘updateNode’ function
to change the value of a specific node. The program can be used as an
independent program for updating and displaying data in a binary tree structure.
The methodology used was a binary tree data structure and preorder traversal. The
results of this program are a functional binary tree with the ability to update specific
nodes, and a preorder traversal display of the tree.
INORDER TRAVERSAL
1. Write a program that simulates the process of pruning a tree. The program should
be in a tree-like structure, with each node storing a random generated data of 7
numbers and a name. The program should have the ability to remove a specific
branch of the tree taken from the user, display the data in pre-order traversal and
search for a specific node by name.
The problem addressed in this code is the simulation of pruning a tree. The program
uses a tree-like structure, with each node storing a random generated data of 7
numbers and a name. The program has the ability to remove a specific branch of
the tree taken from the user, display the data in pre-order traversal and search for a
specific node by name. The importance of this concept is its application in tree
pruning, which is necessary in various fields such as horticulture and computer
science. The program was implemented using a binary tree data structure and pre-
order traversal. The solution was successful in creating a tree-like structure,
removing a specific branch, displaying the data in pre-order traversal and searching
for a specific node by name. The program can be used as an independent program
for tree pruning simulations.
2. Write a program for a family tree given the name a generated the by user with its
first name and last name and organize the tree in alphabetical order by last name.
The program should use a Node class to store the name and last name of each
family member and a Tree class to define the family tree.
The problem is to create a family tree data structure and organizes it in alphabetical
order by last name. It uses a Node class to store the name and last name of each
family member and a Tree class to define the family tree. The program is able to
add nodes to the tree and print it out in the desired order. It can be used as an
independent program for organizing and displaying family tree information. The
methodology used is a binary search tree and in-order traversal. The result of this
program is an efficient way of organizing and displaying family tree information in
alphabetical order.
POSTORDER TRAVERSAL
Sample:
1. Write a program that creates a binary tree containing seven nodes, where each
node contains a value input by the user. The program should traverse the tree in a
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
84
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
post-order format, summing up the value of all nodes, and printing out the value of
each node in the correct format.
2. Write a program to create a room scheduler that displays the availability of each
room with their corresponding numbers and a duration for each room. The program
must prompt the user to enter the room number and range of time to be used, it
must not accept the same input value of the room.
The problem is to show the availability of the rooms, allowing for a countdown timer
to be set for each room. The program contains input parameters such as room
number (integer type) and the duration of time (integer type) to be used.
This concept is important because it allows for the efficient scheduling of multiple
rooms while avoiding conflicts. This product can be used as an independent
program, with the methodology used being object-oriented programming to
structure the data and create an efficient scheduling system. The results were
successful, as the program was able to schedule two rooms and have a countdown
timer for each room.
Code:
PREORDER TRAVERSAL
Employee Performance
class Employee:
# Class representing an employee with a name and a performance rating
def __init__(self, name, performance_rating):
# Driver Code
if __name__ == '__main__':
# Creating a binary tree
root = Employee("John", 4.5)
root.left = Employee("Jane", 3.5)
root.right = Employee("Paul", 4.5)
root.left.left = Employee("Randy", 3.0)
root.left.right = Employee("Sam", 4.0)
Inventory
import random
class Node:
# Class representing a node in a binary tree
def __init__(self):
# Initialize the node with data and children set to None
self.data = random.randint(1,20)
self.left = None
self.right = None
# Driver code
if __name__ == "__main__":
# Create a binary tree
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
86
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
root = Node()
root.left = Node()
root.right = Node()
root.left.left = Node()
root.left.right = Node()
root.right.left = Node()
root.right.right = Node()
INORDER TRAVERSAL
Tree Pruning
import random
#Function to remove the branch of the node with the given name
def removeBranch(root, node_name):
#root exists
if root:
#if the root name matches the given name
if root.name == node_name:
#set the data to an empty list
root.data = []
else:
#call the function recursively for the left and right children
removeBranch(root.left, node_name)
removeBranch(root.right, node_name)
return node_list
#Create the root node with the given data and name
root = Node(random.sample(range(1, 30), 7), "A")
#Call the removeBranch function to remove the branch with the given name
removeBranch(root, node_name)
Family Names
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
88
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
# Define a function to print out the family tree in alphabetical order by last name
def printTree(self, node):
if node is not None:
self.printTree(node.left)
print(node.name + " " + node.lastname)
self.printTree(node.right)
print("Nancy Jones")
print("Peter Brown")
print("Molly Anderson")
POSTORDER TRAVERSAL
Node Calculation
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
# Visit root node, add its value to the total, and print its value
total += root.value
print(root.value, end=" ")
# Return the total value of all the nodes
return total
if __name__ == '__main__':
# Prompt user to enter values for each node in the binary tree
root = Node(int(input("Enter value for root node: ")))
root.left = Node(int(input("Enter value for left child of root: ")))
root.right = Node(int(input("Enter value for right child of root: ")))
root.left.left = Node(int(input("Enter value for left child of left child of root: ")))
root.left.right = Node(int(input("Enter value for right child of left child of root: ")))
root.right.left = Node(int(input("Enter value for left child of right child of root: ")))
root.right.right = Node(int(input("Enter value for right child of right child of root:
")))
Room In use
import time
def input_rooms():
rooms = []
# Create an infinite loop
while True:
# Ask the user to enter the room number
number = input("Enter the number of the room (or enter to finish): ")
if not number:
break
# Check same inputs and display error
if any(x.number == number for x in rooms):
print("Error: Room is already in use.")
# Continue to the next iteration of the loop
continue
The code is a program that creates a binary tree of employees and performs a pre-order
traversal to display the name and performance rating of each employee. The goal of the
program is to display the performance of employees in a hierarchical structure, where
the root node represents the manager, and the left and right children represent the
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
92
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
employees under the manager. The hypothesis is that the pre-order traversal will
display the employees' performance in the hierarchical structure.
The first step is to define the Employee class, which has a name and performance
rating as attributes. It also has left and right children attributes that are set to None. The
class has an init function that initializes the name and performance rating of the
employee, and the left and right children attributes.
class Employee:
def __init__(self, name, performance_rating):
self.name = name
self.performance_rating = performance_rating
self.left = None
self.right = None
The next step is to define the ‘preOrder’ function, which takes the root of the tree and a
counter as inputs. The function checks if the tree exists and if it does, it prints the
employee name and performance rating. It then calls the preOrder function recursively
for the left and right children of the current node. The counter variable is used to keep
track of the position of the employee in the tree.
In the driver code, the binary tree is created with John as the root, Jane and Paul as his
left and right children respectively, Randy and Sam as the left and right children of Jane.
The ‘preOrder’ function is called with the root of the tree and it performs the pre-order
traversal to display the name and performance rating of each employee.
if __name__ == '__main__':
# Creating a binary tree
root = Employee("John", 4.5)
root.left = Employee("Jane", 3.5)
root.right = Employee("Paul", 4.5)
root.left.left = Employee("Randy", 3.0)
root.left.right = Employee("Sam", 4.0)
The results of the program are the pre-order traversal of the employee performance,
where the employees are displayed in the hierarchical structure with the manager at the
top and the employees under him.
Output:
Preorder traversal of employee performance is
Employee 1: John
Performance rating: 4.5
Employee 2: Jane
Performance rating: 3.5
Employee 4: Randy
Performance rating: 3.0
Employee 5: Sam
Performance rating: 4.0
Employee 3: Paul
Performance rating: 4.5
If other methods or equipment were used, the results might not be the same, as the pre-
order traversal displays the employees in a different order than other traversals like the
in-order or post-order traversal. The results of this program correlate with the general
theory of pre-order traversals, where the root node is visited first, followed by the left
and right children.
Inventory
The goal of this code is to create a binary tree, perform a pre-order traversal to display
the data of each node, and then allow the user to update the data of a specific node in
the tree by inputting the node's number. The hypothesis is that the code will correctly
traverse the tree and update the data of the chosen node.
The code begins by creating a ‘Node’ class. It has an initializer method that creates a
new node and sets its data to a random value between 1 and 20, and its left and right
children to None.
Class Node:
def __init__(self):
self.data = random.randint(1,20)
self.left = None
self.right = None
preOrder(tree.left, 2*counter)
preOrder(tree.right, 2*counter + 1)
Another ‘updateNode(tree, counter, data)’ function is defined, which updates the data of
a specific node in the tree. The function takes the root of the tree, a counter value
specifying which node to update, and the new data for that node. It uses recursion to
traverse the tree and find the specified node. The function checks if the current node is
the one to be updated, and if so, sets its data to the new value. If not, it recursively calls
the function on the left or right subtree, depending on the value of the counter.
Lastly, the main function of the script creates a binary tree with seven nodes and
assigns random values to each node. It then prints the tree in pre-order format using the
‘preOrder’ function, and prompts the user to enter the index of a node to update and a
new value for that node. The ‘updateNode’ function is called to update the specified
node, and the tree is printed again in pre-order format to show the changes.
if __name__ == "__main__":
# Create a binary tree
root = Node()
root.left = Node()
root.right = Node()
root.left.left = Node()
root.left.right = Node()
root.right.left = Node()
root.right.right = Node()
The program achieves the goal of traversing a binary tree in pre-order and updating a
specific node in the tree. The results are shown step by step as the program runs, first
printing the original tree, then updating a specific node, and finally printing the updated
tree. The program uses recursion to traverse the tree and update the node, which is a
common and efficient method for traversing and manipulating trees. Overall, the
program provides a clear and concise demonstration of how to traverse and update a
binary tree in Python.
Output:
Original tree:
Node 1: 6
Node 2: 20
Node 4: 14
Node 5: 4
Node 3: 7
Node 6: 15
Node 7: 13
Enter node to update (1-7): 6
Enter new value for node: 21
Updating Node 1 with 21
Updated tree:
Node 1: 6
Node 2: 20
Node 4: 14
Node 5: 21
Node 3: 7
Node 6: 15
Node 7: 13
If other methods or equipment were used, the program could still achieve the same goal
of creating a binary tree, traversing it in pre-order and updating a specific node, but the
implementation would be different. For example, instead of using recursion to traverse
the tree, an iterative approach such as using a stack could be used. The results of the
program would still be the same, however, the time and space complexity of the
program could be affected.
INORDER TRAVERSAL
Tree Pruning
Based on the problem, the program allows the user to remove a branch of the tree by
inputting the name of a node. The program also performs an in-order traversal of the
tree and prints the name and data of each node in the tree.
The problem was solved by First creating a class Node to store the data and a name.
This class also contains left and right pointers which will be used to traverse the tree.
class Node:
def __init__(self, data, name):
self.data = data
self.name = name
self.left = None
self.right = None
Next, I created a function “removeBranch” that takes the root of the tree and the name
of the node to remove as parameters. This function will traverse the tree and find the
node with the given name and set the data of that node to an empty list and set the left
and right children to None.
I then created a function inOrderTraversal to traverse the tree in an in-order manner and
print the data of the nodes. This function will traverse the left subtree, print the node's
name and data, and then traverse the right subtree.
def inOrderTraversal(root):
if root and root.data:
inOrderTraversal(root.left)
print(f"{root.name}: {root.data}")
inOrderTraversal(root.right)
if root:
inOrderTraversalWithoutData(root.left, node_list)
node_list.append(root.name)
inOrderTraversalWithoutData(root.right, node_list)
return node_list
This part of the code, the main function creates the root node with the given data and
name, and assigns the left and right children. Then it prints the list of node names in an
in-order traversal by calling “inOrderTraversalWithoutData” function, and prints the data
of the nodes by calling “inOrderTraversal” function. Then it prompts the user to enter the
name of the node to remove and calls the “removeBranch” function to remove the
branch with the given name. Finally, it prints the updated tree by calling
Output:
In-ordered Traversal: ['H', 'D', 'B', 'E', 'A', 'F', 'C', 'G']
H: [15, 19, 3, 9, 7, 8, 11]
D: [2, 25, 22, 12, 9, 15, 16]
B: [2, 29, 15, 13, 6, 8, 23]
E: [18, 2, 11, 26, 4, 12, 28]
A: [7, 10, 2, 17, 20, 26, 21]
F: [16, 6, 3, 23, 17, 7, 9]
C: [28, 29, 19, 27, 1, 13, 20]
G: [29, 15, 19, 28, 1, 3, 11]
Please enter the name of the node to remove: C
The goal of this script was to demonstrate the ability to remove a specific branch in a
binary tree using recursion, and to traverse the tree in-order and print the data of nodes.
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
98
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
The hypothesis was that the script would be able to remove the specific branch and
traverse the tree in-order as expected. The results showed that the script was able to
remove the specific branch and traverse the tree in-order as expected, and it also
demonstrated the ability to create a binary tree with random data and unique names for
each node. If other methods or equipment were used, the program could be
implemented using other data structures like linked lists or hash tables, but the basic
concept of removing a specific branch and traversing the tree in-order would still apply.
Family Names
The goal of this code is to create a family tree data structure, where each family
member is represented by a Node object, and the tree is represented by the Tree class.
The Tree class has the ability to add a new family member to the tree and print the tree
in alphabetical order by the last name of each family member.The hypothesis is that the
Tree class is able to correctly add new family members to the tree and print the tree in
alphabetical order by last name.
First a class Node if define. It is used to create objects for each member of the family
tree. The class has an initializer method,’ __init__(self, name, lastname)’, that takes in a
name and lastname as arguments, and sets them as attributes of the object. It also sets
the left and right attributes to None, which will be used later to connect the members of
the family tree.
class Node:
def __init__(self, name, lastname):
self.name = name
self.lastname = lastname
self.left = None
self.right = None
Then a class, Tree, is defined which used to create the family tree itself. The class has
an initializer method, ‘__init__(self)’, that sets the root attribute to None, which will be
used later to keep track of the root of the tree.
class Tree:
def __init__(self):
self.root = None
The class also has two methods, ‘addNode(self, name, lastname)’ and ‘printTree(self,
node)’. The first method is used to add new members to the tree. It takes in a name and
lastname as arguments, and creates a new Node object with these attributes. It then
compares the lastname of the new member with the lastnames of the members already
in the tree, and places the new member in the correct position in the tree, following a
binary search tree format.
if self.root is None:
self.root = newNode
else:
current = self.root
while True:
if newNode.lastname < current.lastname:
if current.left is None:
current.left = newNode
break
else:
current = current.left
else:
if current.right is None:
current.right = newNode
break
else:
current = current.right
The second method is used to print out the tree in alphabetical order by last name. It
takes in a node as an argument, and recursively calls itself on the left and right children
of the node, printing out the node's name and lastname after visiting its left subtree, but
before visiting its right subtree.
A new Tree object is created that will contain the nodes for the tree, it is done by using
‘addNode’ function.
tree = Tree()
tree.addNode('John', 'Smith')
tree.addNode('Nancy', 'Jones')
tree.addNode('Peter', 'Brown')
tree.addNode('Molly', 'Anderson')
Lastly the program will print out results which is in alphabetically order by last name. this
was done by using ‘printTree’ function which first printed the leftmost node, then the
rightmost node, and so on. If I had used a different method or equipment, such as a
hash table, I would have been able to store the nodes in an unordered fashion but
would not have been able to print them in alphabetical order. To conclude, my results
do correlate with the general theory of this question, which is that trees can be used to
store and print data in an organized fashion.
POSTORDER TRAVERSAL
Node Calculation
Based on the problem, it is required to get the input value of each node and calculate
the total sum of the tree. The program should display the format of the node in
postorder traversal and the total sum.
The code starts by defining a Node class which has two attributes: left and right and a
value.
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
This is followed by a postOrderTraversal function which takes a root node and a total
parameter. This function recursively visits the left child, right child and root node of the
tree in that order to traverse the tree in a post order manner. After visiting each node, it
updates the total parameter with the value of the node.
total += root.value
print(root.value, end=" ")
return total
The main code then starts by prompting the user to enter values for each node in the
binary tree. This is followed by printing a message to indicate the post order traversal
format. The postOrderTraversal function is then called with the root node to traverse the
tree and calculate the total value of all the nodes. The total is then printed.
if __name__ == '__main__':
root = Node(int(input("Enter value for root node: ")))
root.left = Node(int(input("Enter value for left child of root: ")))
root.right = Node(int(input("Enter value for right child of root: ")))
root.left.left = Node(int(input("Enter value for left child of left child of root: ")))
root.left.right = Node(int(input("Enter value for right child of left child of root: ")))
root.right.left = Node(int(input("Enter value for left child of right child of root: ")))
root.right.right = Node(int(input("Enter value for right child of right child of root:
")))
total = postorderTraversal(root)
Output:
If a different method or equipment was used, the results would depend on what the
method or equipment is. For example, if a pre order traversal was used, the order of the
nodes would be different and hence the total would be different. The results from this
code correlate with the general theory of post order traversal of a binary tree in that it
prints the nodes in the correct order and calculates the total value of the nodes
correctly.
Room In use
The goal of this code is to create a program that can effectively manage a schedule of
rooms in a hotel, such as those found in a room booking system. The program should
be able to manage the availability of rooms and show the schedule of rooms in post-
order traversal format.
The code starts by defining the Room class which includes an initializer method that
initializes the room number and duration of the room. It also includes left and right
attributes for the room.
class Room:
self.number = number
self.duration = duration
self.left = None
self.right = None
"schedule" dictionary's value for the room's number key to "AVAILABLE". If the
"duration" attribute is not 0, the function sets the value to "IN USE" with the remaining
seconds in the parentheses.
if room.left:
postorder_traversal(room.left, schedule)
if room.right:
postorder_traversal(room.right, schedule)
if room.duration == 0:
schedule[room.number] = "AVAILABLE"
else:
schedule[room.number] = f"IN USE ({room.duration} seconds remaining)"
The input_rooms() function is used to gather user input for the rooms in the program. It
starts by creating an empty list called "rooms" and enters an infinite while loop. The user
is prompted to enter the number of a room. If the user enters nothing, the loop breaks. If
the entered room number is already in use, the program displays an error message and
continues to the next iteration of the loop. If the room number is not in use, the user is
prompted to enter a duration for the room in seconds. A Room object is created with the
given number and duration, and the object is appended to the "rooms" list. Once the
loop breaks, the list of Room objects is then returned.
def input_rooms():
rooms = []
while True:
number = input("Enter the number of the room (or enter to finish): ")
if not number:
break
duration = int(input(f"Enter the duration for room {number} (in seconds): "))
room = Room(number, duration)
rooms.append(room)
return rooms
This part of the code creates an infinite loop that updates the room schedule by calling
the ‘create_schedule’ function with the rooms ‘list; as an argument. The returned
dictionary is assigned to the ‘schedule’ variable and then printed to the console with the
room number and availability. The loop also checks if all of the rooms have a duration of
0, and if so, it exits the loop and prints an exit message indicating that all rooms are now
available and the program is exiting. The ‘time.sleep(1)’ function is used to pause the
loop for 1 second, allowing the schedule to be updated every second.
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
103
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
while True:
time.sleep(1)
schedule = create_schedule(rooms)
print("\nRoom Schedule:")
Output:
Room Schedule:
Room 1: IN USE (1 seconds remaining)
Room 2: IN USE (2 seconds remaining)
Room Schedule:
Room 1: AVAILABLE
Room 2: IN USE (1 seconds remaining)
Room Schedule:
Room 1: AVAILABLE
Room 2: AVAILABLE
Both rooms are now available. Exiting program.
The program is well-organized and easy to understand, with clear variable and function
names. The use of the Room class, postorder traversal, and infinite loop with
time.sleep() function effectively simulates the real-time updating of room availability.
If I were to use a different data structure, such as a queue or stack, it could still traverse
the rooms and update the schedule, but the program may not be as efficient. This
program uses a postorder traversal algorithm which is a good choice for a scheduler
that needs to update the status of rooms. The result of the program does really correlate
with the general theory.
References:
Mazin, J. (2020). Binary Tree Traversal Algorithms in Python. Towards Data Science.
Retrieved from https://towardsdatascience.com/binary-tree-traversal-algorithms-
in-python-9417a750d203
LABORATORY REPORT
No. 15
Heaps
Objectives:
To Develop a comprehensive understanding of the fundamentals of heaps in
Python, including what a heap is, how to create it, and how to manipulate it using
basic operations.
To understand the fundamental concepts and functionality of heaps in Python
and how they can be implemented in various algorithms and data structures.
Abstract:
Heaps are a specific type of data structure that can be used to store and
efficiently access data in a certain order. In Python, the heapq module provides a built-
in implementation of heaps, allowing for easy manipulation and access of data in a
heap. Heaps can be used for a variety of tasks, such as sorting and finding the
minimum or maximum element in a large dataset. Additionally, they can be used in
algorithms such as Dijkstra's shortest path algorithm and Huffman coding. Overall,
heaps are a powerful tool for optimizing data manipulation and access in Python.
1. A family is planning their daily activities for the week and wants to use a program to
help them keep track of the events. The program should allow them to add an event,
delete an event, list all the events, and quit the program. It should also requires the
user to add the date and time of the event. Write a that can take events or a
scheduler program.
The problem was to create a program that allows the user to add, delete, and display
events with associated dates and times. This concept is important for helping people
efficiently manage their time and organize their activities. The solution was to utilize
the heapq, datetime, and timedelta libraries along with a while loop to iterate through
user commands. This product can be used as an independent program and the
methodology used was to create a max heap to store the events and use the
datetime library to convert user input into a readable format. The results of the
program are that it allows the user to add, delete, and list events with associated
dates and times. Conclusions can be drawn that this program can help users manage
their time and plan their activities.
2. John has to keep track of his budgeting and wants to use a program to help him. He
needs a program that will track his expenses and incomes and calculate the balance
afterwards. The program should prompt John to enter a transaction and the amount
and description of the transaction. Then it should calculate the total expenses, total
income and balance. Write a program that will help John track his budget.
The concept of this code is important because it provides a useful solution for budget
management. It was designed to solve a problem for an individual, John, who needed a
program to keep track of his expenses and incomes and calculate the balance
afterwards. It was successful in solving this problem as it prompts John to enter a
transaction and the amount and description of the transaction and then calculates the
total expenses, total income, and balance. The methodology used was heapq, which is
a library used for heap sort algorithms, and it was used to efficiently sort the expenses
and income data according to the amount. The results of this program are that it is able
to accurately calculate the total expenses, total income, and balance and display a
summary of the transactions.
Code:
Notes your Event
import heapq
from datetime import datetime, timedelta
def event_scheduler():
# Initialize empty max heap to store the events
events = []
while True:
# Print the menu
print("\nMenu:")
print("A - Add event")
print("D - Delete event")
print("L - List events")
print("Q - Quit")
# If the user wants to add an event, prompt them to enter the event details
event = input("Enter an event: ")
date_str = input("Enter the date and time of the event (format: YYYY-MM-DD
HH:MM): ")
date = datetime.strptime(date_str, "%Y-%m-%d %H:%M")
time_until_event = (date - datetime.now()).total_seconds()
# Convert the max heap to a list, delete the specified event, and convert it
back to a max heap
event_list = list(events)
del event_list[index]
heapq.heapify(event_list)
events = event_list
Transaction Tracker
import heapq
def budget_management():
# Initialize empty min heap for expenses and max heap for income
expenses = []
income = []
while True:
# Prompt the user to enter a transaction (expense or income)
type_ = input("Enter E for expense or I for income, or Q to quit: ")
if type_.upper() == "E":
while expenses:
# Remove and print the smallest element from the expenses heap
amount, description = heapq.heappop(expenses)
print(f"- {amount}: {description}")
print(f"Total income: {total_income}")
print("Income:")
while income:
# Remove and print the largest element from the income heap
amount, source = heapq.heappop(income)
print(f"- {amount}: {source}")
print(f"Balance: {balance}")
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
108
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES
References:
Alsweiler, D. (2020). Heap Data Structure in Python. Retrieved from
https://www.geeksforgeeks.org/heap-data-structure/
Guido van Rossum (2020). The Python Tutorial. Retrieved from
https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-queues
(StackExchange, 2018, "Implementing Heap in Python,"
https://codereview.stackexchange.com/questions/156027/implementing-heap-
in-python)