Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 109

PANGASINAN STATE UNIVERSITY

URDANETA CITY CAMPUS


COLLEGE OF ENGINEERING AND ARCHITECTURE
DEPARTMENT OF COMPUTER ENGINEERING
FIRST SEMESTER, ACADEMIC YEAR 2022-2023

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.

1 Python Programming Environment

Keywords & Identifiers


2
Statements and Comments
Variables
3
Data Type Conversion

4 Operators

5 Functions

6 String / List

7 Tuple / Dictionary

If else
8
For loop
While loop
9
Break/Continue/Pass Statements

10 Linear Search Algorithm

11 Binary Search Algorithm

12 Stacks

13 Queues/ Dequeues

Preorder Traversal/
14 Inorder Traversal/
Postorder Traversal

15 Heaps

TOTAL

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT 2
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 1
Python Programming Environment

Objectives:

 To be able to know the use of Python programming language


 To acquire basic knowledge in using Python IDE

Abstract:

Python is a high-level, general-purpose programming language, which means


that it can be used to create a variety of different programs and is not specialized for
any specific problems. Its design philosophy emphasizes code readability with the use
of significant indentation. It is often used to build websites and software, automate
tasks, and conduct data analysis.
To be able to create projects using the Python programming language, it is necessary to
have an Integrated Development Environment (IDE), a software that consolidates the
basic tools needed for software testing and writing. It has the features of a text editor,
compiler, or interpreter, build or make integration, debugger, syntax highlighter,
graphical user interface (GUI), and other possible new features, which makes it more
convenient for you when creating your projects. In this part, we will be using PyCharm
as our Integrated Development Environment (IDE). The figure below shows the basic
parts of the Python IDE.

To begin in our first sample code, we should first create a new project showing the
following steps:

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT 3
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT 4
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

Step 4: Select the option Python File from the context menu, and then type the new
filename.

PyCharm creates a new Python file and opens it for editing.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT 5
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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”.

To run our code there are 3 methods:

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()

Results and Discussions:

We defined Python as a high-level, general-purpose programming language that


gives users the opportunity to explore the world of programming. It comes with an
Integrated Development Environment (IDE) where you can develop or start your own
project, such as PyCharm software. There are different kinds of IDEs which you can use
to create projects in Python and choosing among them is your choice. To create our
code, we must create a new project in PyCharm.

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/

Wikipedia (n.d.). Python (programming language). Retrieved from


https://en.wikipedia.org/wiki/Python_(programming_language) Coursera (n.d.).

What Is Python Used For? A Beginner’s Guide. Retrieved from


https://www.coursera.org/blog/what-is-python-used-for/

Finxter (n.d.). Writing, Running, Debugging, and Testing Code In PyCharm. Retrieved
from https://finxter.com/pycharm-run-debug-test/

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT 7
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 2
Keywords, Identifiers, Statements and Comments

Objectives:

 To be familiar with keywords, identifiers, statements, and comments in Python


programming. 
 To be able to construct a code using those 4 concepts in Python.

Abstract:

KEYWORDS

Keywords in Python are reserved words that cannot be used as ordinary


identifiers (e.g. False, True, print, id, and, or, not, etc.). They must be spelled exactly as
they are written.

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

A Python identifier is a name used to identify a variable, function, class, module,


or other object. An identifier starts with a letter A-Z or a-z, followed by zero or more
letters, underscores, and digits (0 to 9). Examples of identifiers would be 'my_variable',
'my_function', 'my_class', and 'my_object'. Python does not allow punctuation
characters such as @, $, and % within 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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT 8
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

variables are Employee_ID, Employee_Salary and Tax_Income. User input is


required for the values of Employee_ID and Employee_Salary.

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:

Income Tax = Salary - Salary * 5%


Net Salary = Income Tax - Income Tax * 2%

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:

Celsius = (Fahrenheit - 32) * 5/9

This concept is important because it is a necessary tool to accurately convert


temperatures between Fahrenheit and Celsius. This code was able to solve the
problem, but product cannot be used as an independent program, as it only
contains code to convert temperatures. The results showed that the code was able
to accurately convert temperatures between Fahrenheit and Celsius.

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT 9
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

In writing a program it is important leave an information about it using comments.


We use single-line comment that starts with hashtag symbol ‘#’ with no white spaces
and lasts till the end of the line. Multi-line comments can be used by enclosing multiple
hashtags ‘###’ or triple quotes ‘’’, in each and every line will be considered as a single
comment. Also, comments can also be used to prevent Python from executing code.

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.

The problem is to calculate the area of a circle, and it is defined as the number of


square units inside that circle multiply with the value of pi. Hence, the output
parameter is identified an integer type. The mathematical formula to calculate the
Area of a Circle is:
Area = π * (radius)2

Codes:

KEYWORDS
Match the Passwords

# Ask user to enter a password


pwd1 = input("Enter a password: ")

# Ask user to enter the password again


pwd2 = input("Re-enter the password: ")

# Check if the two passwords match


if pwd1 == pwd2:
print("Password Match")
else:
print("Passwords don't match")

Arithmetic Sequence

# Calculates the numbers in arithmetic sequence


arithmetic_seq = lambda x: x + (x - 1) * (2)

# Checks the number between 2 to 9


for num in range(2, 9):
print(arithmetic_seq(num), end=' ')

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
10
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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"))

# Deducting the income tax and loan to the salary


Tax_Income = Employee_salary - Employee_salary*(0.05)
Total = Tax_Income - Tax_Income*(0.02)
print("Net Salary: PhP", Total)

# Calls out the function


Net_Salary()

Fahrenheit to Celsius

# Takes inputs from the user


Fahrenheit = int(input("Enter Fahrenheit Temperature: "))

# Convert the input to Celsius


Celsius = (Fahrenheit-32)*(5/9)

# Prints the converted value with 2 decimal places


print(Fahrenheit, "⁰F", "is equal to", "{:.2f}".format(Celsius),"⁰C")

STATEMENTS
Sum of two integers

# Function that adds two integers


def addition(num1, num2):
return num1 + num2

result = addition(5, 10)


print(result)

Sets

# Driver code
set1 = {4, 5, 3, 2, 6, 9}
set2 = {1, 2, 6, 10, 5, 8, 3}

print(set1 & set2) # prints the same value in both sets

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

# Loop will iterate 10 timeswhile i<10:


if i%2 == 0: # checks the number if even
print(i) # print the even numbers
i +=1 # Incrementing the value by one

Radius of the Circle

#Ask user to input radius


radius = float(input("Radius: "))

#Calculates and output the area of circle


print("The area is", 3.14 * radius ** 2)

Results and Discussion:

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
12
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

Radius of the Circle

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
13
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

Lambert, K. A. (2019). Fundamentals of Python: Data Structures (2nd ed.). Cengage


Learning.

Programiz. (2020). Python Identifiers Overview. Retrieved from


https://www.programiz.com/python-programming/identifier

GeeksforGeeks (2020). Python - Keywords. Retrieved from


https://www.geeksforgeeks.org/keywords-in-python/

Arithmetic Sequence Formula - What is Arithmetic Sequence Formula? Examples


(Cuemath.com). (n.d.). Retrieved from https://www.cuemath.com/arithmetic-
sequence-formula/

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
14
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 3
Variables, Data Type Conversion

Objectives:

 To learn to use variables to store and retrieve data.


 To develop understanding in converting values in different data types.
 To practice the use of built-in functions for data type conversion.

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.

2. You are an IT manager at a tech company that specializes in software


development. Your company has recently been assigned a project to create a new
capstone project that utilizes the following: data, technology, AI, research, analysis,
programming, design, development, systems, software, security, networking, cloud,
robotics, hardware, web, mobile, and database that are stored in variable ‘noun’.
You need to come up with a title for the capstone project. Write a program that
randomly selects a verb from the (verbs= ["Exploring", "Enhancing", "Developing",
"Designing", "Implementing", "Analyzing", "Testing", "Managing", Optimizing",
"Integrating", "Deploying", "Securing", "Automating", "Innovating"]) list and a noun
from the 'nouns' list to create a title for a capstone project. The output should be a
string composed of the verb, the noun, and the word "Capstone".

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
15
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

DATA TYPE CONVERSION

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

# Importing required modules


import matplotlib.animation as animation
import matplotlib.pyplot as plt

# 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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
16
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

plt.title("Population Growth")
plt.xlabel("Year")
plt.ylabel("Population (in billions)")

# Create figure and axes


fig, ax = plt.subplots()
ax.set_xlim(1999, 2021)
ax.set_ylim(70, 110)
line, = ax.plot([], [], lw=2)

# 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,

# Design the graph


anim = animation.FuncAnimation(fig, animate, init_func=init, frames=21, interval=200,
blit=True)

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"]

# Generate a random title and print the output


title = random.choice(verbs) + " " + random.choice(nouns) + " " + "Capstone"
print(title)

DATA TYPES CONVERSION


Secret Message

# Takes input
Text = str(input("Enter Text: "))

# Split string into a list of words


COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
17
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

List_of_Words = Text.split()

#List to contain first letter of each word


List_of_letters = []

# Iterate over all words in list


for word in List_of_Words:
# select first letter of each word, and append to list
List_of_letters.append(word[0])
# rejoin the letters and convert to hex value
First_Letters =''.join(List_of_letters)
Convert_toAscii = [hex(ord(char)) for char in First_Letters]

print("Letter: \n",Convert_toAscii)
print(First_Letters)

Bank’s Data

# Import the required modules


import sys

# Initialize an empty string


encoded_str = ""

# Get the plain text from user to encrypt


plain_text = str(input("Enter Text to Encrypt(lowercase): "))

# Loop through all chars in the plain text


for char in plain_text:
# convert the char to ASCII code
asc_code = ord(char)

# convert the ASCII code to EBCDIC code


ebcdic_code = asc_code + 64

# convert the EBCDIC code to char


ebcdic_char = chr(ebcdic_code)

# add the char to the encoded string


encoded_str += ebcdic_char

# Define a function for conversion bit configuration (binary value)


def text_to_ebcdic(text):
result = []

# Iterate through each character of the text


for character in text:

# get the EBCDIC value of the character


value = ord(character)

# convert it to binary and append binary value to the list


binary_value = bin(value)[2:].zfill(8)
result.append(binary_value)
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
18
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# return the result list


return result
# Print the equivalent bit of each letter
print('Bit Configuration: ',text_to_ebcdic(plain_text))

# 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

print('Number of Total Bits: ', get_bit_length(plain_text))


print("Encrypted Text to EBCDIC: " + encoded_str)

Results and Discussion:

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

DATA TYPE CONVERSION


Secret Message

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:

GeeksforGeeks (n.d.). hex() function in Python. Retrieved from:


https://www.geeksforgeeks .org/hex-function-python/

GeeksforGeeks: "Type Conversion in Python" Retrieved from:


https://www.geeksforgeeks.org/type-conversion-in-python/

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
20
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

Linode. (n.d.). Converting Data Types in Python. Retrieved from:


https://www.linode .com/docs/development/python/converting-data-types-in-
python/

Population growth in the Philippines (worlddata.info) (2020). Retrieved from:


https://www.worlddata.info /asia/Philippines/population-growth.php

Pynative.com (n.d.). Python Functions Exercise with Solution [10 Programs]. Retrieved
from: https://pynative.com/ python -functions-exercises-solutions/

Python Guides (n.d.). Python Convert Binary To Decimal + 15 Examples. Retrieved


from: https://www.python-guides.com/2020/03/python-convert-binary-to-
decimal/

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/

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
21
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 4
Operators

Objectives:

 To develop an understanding of the different types of Python operators and how


to use them effectively in an application.
 To utilize the proper Python operators for efficient code execution and
optimization.

Abstract:

Python Operators are symbols that allow us to perform operations on variables


and values. They enable us to write concise and efficient code. Python has several
different types of operators, including arithmetic, comparison, assignment, logical,
bitwise, and membership operators. Each of these operators performs a specific task,
such as performing arithmetic calculations, comparing values, assigning values, and
performing logical operations. The use of these operators is essential when writing
Python code, as they allow us to manipulate data and perform operations quickly and
easily.

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
22
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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()

Least Common Multiple

# Take two input numbers from the user


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Create a list of numbers from 1 to 100


list_of_nums = [i for i in range(1, 101)]

# Create an empty list to store the least common multiple


lcm_list = []

# Iterate through the list of numbers


for i in list_of_nums:
# check if the number is divisble by both numbers
if (i % num1 == 0) and (i % num2 == 0):
# append the number to the lcm_list
lcm_list.append(i)

# Print the least common multiple


print("The least common multiple is:", min(lcm_list))

Results and Discussion:

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.

Least Common Multiple

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:

Lambert, K. A. (2019). Fundamentals of Python: Data Structures (2nd ed.). Cengage


Learning.

Goodrich, M. T., Tamassia, R., & Goldwasser, M. H. (2013). Data Structures and
Algorithms in Python. John Wiley & Sons, Inc.

Python Operators - W3Schools. (2020). W3schools.com. Retrieved from:


https://www.w3schools.com/python/python_operators.asp 2.

Python Operators - Tutorialspoint. (2020). Tutorialspoint.com. Retrieved 20 October


2020, from https://www.tutorialspoint.com/python/python_operators.htm

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
24
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 5
Functions

Objectives:

 To develop an understanding of the syntax and structure of Python functions.


 Construct and call functions in Python, including the ability to pass arguments
and return values.

Abstract:

In the context of programming, a function is a named sequence of statements


that performs a computation. When you define a function, you specify the name and the
sequence of statements. Later you can “call” the function by name. It is common to say
that a function “takes” an argument and “returns” a result. The result is called the return
value.

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.

2. A physics student is having difficulty understanding the relationship between


Coulombs and electrons. Write a program that calculate the equivalent electron
charge when the number of coulombs is given as input in integer type. Note that 1
Coulomb is equivalent to 6.242 x 10 18 electrons. Solution in calculating the
equivalent electron must be shown.

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
25
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

Code:

Number of Days Left

from datetime import date as date_n

# Function to get no. of days between given dates


def num_days(date_one, date_two):
return (date_two - date_one).days

# Store the dates in range of date1 to date 2


date_one = date_n(2022, 11, 28)
date_two = date_n(2023, 2, 14)
print("The Number of Days are: ", num_days(date_one, date_two), "days")

Electron Charge

# Function to find equivalent electron charge of the input


def electron_charge(coulomb):
return coulomb*6.24150934*10**18

# Input the value of coulomb


coulomb = float(input("Enter the value of Coulombs: "))

# Calculating the equivalent electron charge


charge = electron_charge(coulomb)

# Printing the equivalent electron charge


print('Solution: \n', "e =",coulomb, "x 6.242x10^18")
print("Equivalent electron charge of "+str(coulomb)+" coulomb is "+str(charge)+"
e.")

Results and Discussion:

Number of Days Left

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
26
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

To wrap it up, in this lab I learned the importance of utilizing functions in a


program for various reason. By creating a new function, it allows you to name a group of
statements, thereby making your program easier for others to understand and debug.
Additionally, it can make a program more concise by eliminating redundant code.

References:

Python datetime Module - Python datetime Class (2021, April 28). GeeksforGeeks.
https://www.geeksforgeeks.org/python-datetime-module/

Python - Date & Time (2021, April 28). W3schools.


https://www.w3schools.com/python/python_datetime.asp

JustinTOOLs.com (n.d.). Convert Electron Charge to Coulombs (e- to C). Retrieved


June 8, 2020, from
https://www.justintools.com/electricity-and-magnetism/electron-charge-to-
coulombs.php

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
27
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
28
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

# Define a function that takes two inputs “string” and “vowels”


def Check_Vow(string, vowels):
# list that will contains all characters in the input and prints the length
final = [each for each in string if each in vowels]
print("There are total of", len(final), "vowels in the string")

# Driver Code
string = "Peter Picked a Peck of Pickled Peppers"
vowels = "AaEeIiOoUu"
Check_Vow(string, vowels);

Reverse the words

a = "This is a string"
b = ''

# Finds the index of the last character in the string ‘a’


i = len(a) - 1

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
29
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# Starts a loop that runs if the index 'i' is greater or equal to 0


while (i >= 0):
# adds the character at index 'i' in the string 'a' to the variable 'b'
b = b + a[i]
# decrements the index 'i' by 1
i=i-1

print("Result = ", b)

LIST
Passed or Failed

# List to store the grades of a student


Grade=list()

# Input to enter the number of subjects


n=int(input("Enter how many subjects: "))

# Prompt the user to enter the grades


print("Enter the Grades:")

# Loop to iterate for n times, the number of subjects


for i in range(int(n)):
x=int(input(""))
Grade.append(int(x)) # append the grade to the list

# Calculates the sum and average of the grades


sm=sum(Grade)
avg=sm/n
print("GENERAL AVERAGE: ",avg)

# Checks if the calculated average is passed of failed


if avg < 75:
print("Failed")
else:
print("Passed")

Median

import statistics

# Create a list
Num_list = [32, 42, 46, 46, 54]

# Get the median


print(statistics.median(Num_list))

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
30
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

Results and Discussion:

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.

Reverse the words

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:

"Median." statistics — Mathematical statistics functions,


docs.python.org/3/library/statistics.html.

W3Schools. (2020). JavaScript Lists. Retrieved from https://www.w3schools.com/js/


js_arrays.asp

Munshi, A. (2020). Reverse a String in Python. Retrieved from


https://www.programiz.com/python-programming/examples/reverse-string

Educba.com (n.d.). Python String Manipulation: Working of String Manipulation with


Example. Retrieved from https://www.educba.com/string-manipulation-in-
python/
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
31
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

W3schools. (2020). Python Strings. W3schools. https://www.w3schools.com/python


/pythonstrings.asp

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
32
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 7
Tuple and Dictionary

Objectives:

 To Utilize tuples in Python to store and access multiple values efficiently.


 Create dictionaries in Python to map keys to values for easy data retrieval.
 To understand the differences between tuples and dictionaries and how to use
them in various contexts.

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
33
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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: ")

# Create tuples from the inputs


input_tuple1 = tuple(int(val) for val in point1.split())
input_tuple2 = tuple(int(val) for val in point2.split())

# Compute the distance between point1 and point2


distance = math.sqrt((input_tuple1[0]-input_tuple2[0])**2 + (input_tuple1[1]-
input_tuple2[1])**2)

# Print the distance with 2 decimal places


print("{:.2f}" .format(distance))

Gift Card Registration

# Prompts user to enter a quantity of IDs to be registered


num = int(input("Enter quantity of ID to be registered: "))

store = () # empty list to store the input IDs

# Loops through the number of IDs that are to be entered


for i in range(1, num+1):
info = int(input("Enter ID. : ")) # prompts the user to enter each ID
store+=(info,) # adds the IDs to the tuple

# Prints out the tuple of registered IDs


print("Successfully Registered: \n",store)

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
34
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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?")

# prompts user to enter the answer


ans1 = int(input("\nKevin's Age is: "))
ans2 = int(input("\nMargaret's Age is: "))

# condition that checks the input


if age["Kevin"] == ans1 and age["Margaret"] == ans2:
print("\nCongrats! You got the correct ages!")
elif age["Kevin"] != ans1 and age["Margaret"] == ans2:
print("Kevin's Age is wrong!")
else:
print("Margaret's Age is wrong!")

# Call the code


code()

Movie Search

# Options is a dictionary with 5 key-value pairs


options = {"Comedy": "The Red Notice",
"Adventure": "Miss Peregrine's",
"Horror": "Orphan",
"Science Fiction":"The Adam Project",
"Historical": "Dunkirk"}

# Prompt the user to enter a search query


enter = input("Search Genre: ")

print(options.get(enter, "Not found"))

Results and Discussion:

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.

Gift Card Registration

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:

Let x be Kevin’s present age.


Then Margaret’s present age is: x-4
Next year Kevin will be x+1 years old, and Margaret will be x-4+1=x-3 years old
Since next year Kevin will be 2 times as old as Margaret, you can write the equation:
x+1=2*(x-3)
Solving the equation:
x + 1 = 2x - 6
1 + 6 = 2x - x
x=7 thus, you got Kevin’s age.
To check for Margaret’s age: x - 4  7 - 4 = 3

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:

Aquino, M. G. (n.d.). Age Problems. Retrieved April 28, 2021, from


https://www.academia.edu /36050433/Age_problems

Lambert, K. A. (2019). Fundamentals of Python: Data Structures (2nd ed.). Cengage


Learning

Downey, A. (2012). Think Python: How to Think Like a Computer Scientist (Version
2.0.17). Needham, Massachusetts: Green Tea Press

Python Tuples: A Complete Guide (2020). Retrieved from


https://www.guru99.com/python-tuples-tutorial.html

W3Schools (2019). Python dictionaries - access. Retrieved from


https://www.w3schools.com/python/python_dictionaries_access.asp

Python Dictionary (2020). Retrieved from https://www.programiz.com/python-


programming/dictionary

Mueller, M. (2020). The Basics of Python Tuples. Retrieved from


https://www.datacamp.com/community/tutorials/python-tuples-tutorial

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
37
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

The problem is to determine the winner of a game of Blackjack between a player


and a dealer, based on the cards that have been randomly generated. The input
parameters are the player's hand (list type) and dealer's hand (list type), the output
parameter is the winner (string type). During the processing phase, a loop is used to
generate the number of cards and an if-else statement is used to determine the
winner which makes the program. Also, which allows the user to hit or stay. The
result of the program shows the player's and dealer's hands, as well as their scores,
and the winner of the game.

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
38
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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!")

# User inputs date of birth


month = int(input("Month (1-12): "))
day = int(input("Day (1-31): "))

# Checks if input within its range


if month > 12 or day > 31:
print('ERROR: Invalid Input!. Please try again!.')
exit()

# 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!")

# For month of April 20 to May 20


elif month == 4 and day >= 20 or month == 5 and day <= 20:
z_sign = "Taurus"
print("Your Lucky Colors: Pink and Green")
print("Work hard and stay focused.")

# For month of May 21 to June 20


elif month == 5 and day >= 21 or month == 6 and day <= 20:
z_sign = "Gemini"
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
39
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

print("Your Lucky Colors: Yellow and Purple ")


print("Think before you speak.")

# For month of June 21 to July 22


elif month == 6 and day >= 21 or month == 7 and day <= 22:
z_sign = "Cancer"
print("Your Lucky Colors: Silver and White")
print("Be kind and follow your heart.")

# For month of July 23 to August 22


elif month == 7 and day >= 23 or month == 8 and day <= 22:
z_sign = "Leo"
print("Your Lucky Colors: Gold and Orange")
print("Believe in yourself and never give up.")

# For month of August 23 to September 22


elif month == 8 and day >= 23 or month == 9 and day <= 22:
z_sign = "Virgo"
print("Your Lucky Colors: Gold and Orange")
print("Stay organized and stay true to yourself.")

# For month of September 23 to October 22


elif month == 9 and day >= 23 or month == 10 and day <= 22:
z_sign = "Libra"
print("Your Lucky Colors: Pink and Blue")
print("Balance is key.")

# For month of October 23 to November 21


elif month == 10 and day >= 23 or month == 11 and day <= 21:
z_sign = "Scorpio"
print("Your Lucky Colors: Red and Black")
print("Be passionate and never settle.")

# For month of November 22 to December 21


elif month == 11 and day >= 22 or month == 12 and day <= 21:
z_sign = "Sagittarius"
print("Your Lucky Colors: Purple and Orange")
print('"Be optimistic and pursue your passions."')

# For month of December 22 to January 19


elif month == 12 and day >= 22 or month == 1 and day <= 19:
z_sign = "Capricorn"
print("Your Lucky Colors: Brown and Black")
print("Stay determined and don't be afraid to take risks.")

# For month January 20 to February 18


elif month == 1 and day >= 20 or month == 2 and day <= 18:
z_sign = "Aquarius"
print("Your Lucky Colors: Turquoise and Blue")
print("Stay open minded and stay true to your beliefs.")

# For month of February 19 to March 20


elif month == 2 and day >= 19 or month == 3 and day <= 20:
z_sign = "Pisces"
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
40
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

print("Your Lucky Colors: Green and Lavender ")


print("Trust your instincts and follow your dreams.")

print("Zodiac Sign: ", z_sign)


print("Remember, your future depends on you!")

Blackjack

import random

# Initialize player's and dealer's hands with two random numbers


player_hand = []
dealer_hand = []

for i in range(2):
player_hand.append(random.randint(1, 10))
dealer_hand.append(random.randint(1, 10))

# Calculate initial scores


player_score = sum(player_hand)
dealer_score = sum(dealer_hand)

# Print initial hands and scores


print("Player's hand: " + str(player_hand))
print("Player's score: " + str(player_score))
print("Dealer's hand: " + str(dealer_hand))
print("Dealer's score: " + str(dealer_score))

# Game loop
while player_score <= 21 and dealer_score <= 21:
choice = input("Hit or stay? ").lower() # ask player to hit or stay

if choice == "hit": # if chosen hit


# generates random numbers for player and sums it up
player_hand.append(random.randint(1, 10))
player_score = sum(player_hand)
print("Player's hand: " + str(player_hand))
print("Player's score: " + str(player_score))

elif choice == "stay": # if chosen stay


# generates random numbers for dealer and sums it up
dealer_hand.append(random.randint(1, 10))
dealer_score = sum(dealer_hand)
print("Dealer's hand: " + str(dealer_hand))
print("Dealer's score: " + str(dealer_score))

# Condition to determine the winner


if player_score > 21 and dealer_score > 21:
print("It's a draw!")
elif player_score > 21 or dealer_score == 21:
print("Dealer wins!")
elif dealer_score > 21 or player_score > dealer_score or player_score == 21 :
print("Player wins!")

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
41
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

else:
print("Dealer wins!")
FOR LOOP
Guess the Words

# Importing random module to shuffle the letters


import random

# Initializing a list
my_list = ["SKELETON", "NICOTINE", "CONTINENT", "METAMORPHOSIS"]
correct_words = 0 # Initializing a variable

for word in my_list: # Loop through each word in the list


# Shuffling the letters of the word
shuffled_word = ''.join(random.sample(word, len(word)))
print("Guess the word: " + shuffled_word)
answer = input()

# Looping until user enters correct answer


while answer.upper() != word:
print("Incorrect. Try again: ")
answer = input()

# If user enters correct answer


if answer.upper() == word:
correct_words += 1
print("Correct!")

Sea Voyage

# Import needed modules


import matplotlib.pyplot as plt
import numpy as np

# Create empty list for x and y values


xlist = []
ylist = []

# Loop through the range from 1 to 5


for i in range(1, 5):
x = i * 40
xlist.append(i) # append the index value to the x list
ylist.append(x) # append the result of the multiplication to the y list
print(ylist) # print y list

# Convert x and y list to numpy array


x = np.array(xlist)
y = np.array(ylist)

# Plots’ the x and y values as a scatter plot


plt.scatter(x, y)
plt.show

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
42
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

Results and Discussion:

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).

Matplotlib 3.2.2 Documentation. Retrieved from https://matplotlib.org/


3.2.2/api/_as_gen/matplotlib.pyplot.scatter.html

Kumar, A. (2020). Numpy Arrays in Python. Retrieved from


https://www.geeksforgeeks.org/numpy-array-in-python/

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
44
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

2. Write a program that checks if a given number is a Disarium number or not. A


number is said to be Disarium if the sum of its digits powered with their respective
position is equal to the original number.

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
45
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

2. Write a program creating a 3-level authentication system that requires a mother’s


maiden name, favorite number and last four-digit Visa Card to access a secure file.
If a user fails to enter the correct information three times in any level of
authentication, access will be denied and will required to try again after 24 hours.
Assume that the user has already the answers stored in the program.

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:

(A) Fruits (B) Vegetables (C) Condiments (D) Spices


Price Price Price Price
Item Item Item Item
(Php) (Php) (Php) (Php)
Ground
Apple 10.05 Carrots 60 Ketchup 550g 124.32 15.03
Pepper 20g
Chili Powder
Orange 9.05 Potatoes 54.50 Mayo 220ml 65.45 18.25
20g
Fish Sauce Cumin Powder
Pear 12.25 Tomatoes 40 53.45 21.22
350ml 20g
Grapes Onions ¼ Garlic Powder
82.64 23.35 Soy Sauce 1L 60.50 18.05
¼ kg kg 20g

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

# Initialize the traffic light to green


colour = 'green'

# Begin the countdown loop


while True:
# each condition has 5 seconds to run before goes to next
if colour == 'green':
print('GREEN light is on. Countdown begins in 5 seconds...')
time.sleep(5)
colour = 'yellow'
elif colour == 'yellow':
print('YELLOW light is on. Countdown begins in 5 seconds...')
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
47
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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;

num = int(input("Enter a number: "))


rem = sum = 0;
len = calculateLength(num);

# Makes a copy of the original number num


n = num;

# Calculates the sum of digits powered with their respective position


while (num > 0):
rem = num % 10; # takes each digit of number
sum = sum + int(rem ** len);
num = num // 10;

len = len - 1; # decrease the value of the variable 'len' by 1


print(sum)

# Checks whether the sum is equal to the number itself


if (sum == n):
print(str(n) + " is a disarium number");
else:
print(str(n) + " is not a disarium number");

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
48
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# Runs forever
while True:
# generate two random numbers
num1 = random.randint(5, 20)
num2 = random.randint(5, 20)

# get the sum


answer = num1 + num2

# print the question


print("What is the sum of %d + %d ?" % (num1, num2))

# get the start time


start_time = time.time()

# get user input


user_answer = input("Answer: ")

# check if the user entered 'x' to exit the game


if user_answer == 'x':
print("Game over!")
break

# 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

# check the user answer and print time taken to answer


if int(user_answer) == answer:
correct_answers += 1
print("Correct!")
print("Time taken {:.2f}".format(time.time() - start_time),'seconds')
else:
print("Time taken {:.2f}".format(time.time() - start_time),'seconds')
print("Game over!")
print("Your Score is",correct_answers)
break

Authentication Test

a1 = 'Infantes'
a2 = '98'
a3 = '2425'
count = 0
print('To access your information you must pass the three authentication test')

# Loop that gets user input for 3 times if it is wrong


while count < 3:
# question 1
q1 = input("What is your mother's maiden name? ")
if q1 == a1:
print("Passed!")
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
49
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

q2 = input("What is your favorite number? ")


# if the answer in Q1 is correct then proceed to this next Q
if q2 == a2 and q1 == a1:
print("Passed!")

q3 = input("What are the last 4 digits of your Visa Card? ")


# if the answer in Q2 is correct this will be the next and last Q
if q3 == a3 and q2 == a2:
print("Passed!")
print("Access Granted....")
break
# if the answer are wrong if will require to input again.
else:
print("Incorrect!. Please try again.")
count += 1
else:
print("Incorrect!. Please try again.")
count += 1

else:
print("Incorrect!. Please try again.")
count += 1

# Printing message after 2 wrong answers


if count == 2:
print("You have exceeded the maximum attempts. Please try again after 24
hours.")

CONTINUE
SuperMart

# A dictionary for the items and prices


items_dict = {
"A": {"A": 10.05, "B": 9.05, "C": 12.25, "D": 82.04},
"B": {"A": 60.00, "B": 54.50, "C": 40.00, "D": 23.35},
"C": {"A": 124.32, "B": 65.45, "C": 53.45, "D": 60.50},
"D": {"A": 15.03, "B": 18.25, 'C': 21.22, "D": 18.05}
}

print("Welcome to our supermarket!")

total = 0

# Start a while loop for the user to buy items


while True:
print("A => Fruit")
print("B => Vegetables")
print("C => Condiments")
print("D => Spices")

# prompt user to enter input


item_category = input("\nPlease enter the category you'd like to shop in: ")
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
50
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# items in the input category


if item_category == 'A':
print("\nHere's what we have in stock:")
print("A=> Apple: Php 10.05\nB=> Orange: Php 9.05\nC=> Pear: Php
12.25\nD=> Grapes 1/4kg: Php 82.04")

elif item_category == 'B':


print("\nHere's what we have in stock:")
print("A=> Carrots 1/2kg: Php 60.00\nB=> Potatoes 1/2kg: Php
54.50\nC=> Tomatoes 1/4kg: Php 40.00\nD=> Onions 1/4kg: Php 23.35")

elif item_category == 'C':


print("\nHere's what we have in stock:")
print( "A=> Ketchup 550g: Php 124.32\nB=> Mayo 220ml: Php
65.45\nC=> Fish Sauce 350ml: Php 53.45\nD=> Soy Sauce 1L: Php 60.50")

elif item_category == 'D':


print("\nHere's what we have in stock:")
print("A=> Ground Pepper 20g: Php 15.03\nB=> Chili Powder 20g: Php
18.25\nC=> Cumin Powder 20g: Php 21.22\nD=> Garlic Powder 20g: Php
18.05")

# check if input is in the category


elif item_category not in ['A', 'B', 'C', 'D']:
print("Sorry, that is not a valid selection. Please try again.")
continue

# ask the user to input correspondig letter of the item


item_name = input("\nEnter the letter of the item to purchase: ")

# 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

# takes the quantity of the item and check if it is valid


try:
item_quantity = int(input("Enter Quantity: "))

# if quantity is invalid it will go back from the categories


except ValueError:
print("Invalid Quantity! Please try Again.")
continue

# calculate the total amount of the items


total += items_dict[item_category][item_name] * item_quantity
print("Total Cost:", "Php","{:.2f}".format(total))

# ask the user if they'd like to buy again


buy_again = input("Would you like to buy anything else? (y/n): ")

# 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

# continue the loop if the user wants to buy something


else:
continue

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]

print("Sum of the list:", total)


check_num = 2*n # a set equal to double the initial number

#checks the number if deficient


if total > check_num:
print("Number", n, "is not deficient")
elif check_num > total:
print("Number", n, "is deficient")

PASS
Set of Intersection

list_1 = [1, 7, 3, 8, 5]
list_2 = [2, 3, 9, 5, 6]

# Create an empty list to store the new values


list_3 = []
list_4 = []

# Iterate through each list


for i in list_1:
# check if item exists in both lists
if i in list_2:
# If it does, pass it and do nothing
pass
# If it does not exist in the second list, add it to the new list_3
else:
list_3.append(i)

for j in list_2:
# check if item exists in both lists

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
52
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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)

# Output the new values of each list


print("List A:", list_1)
print("List B:", list_2)
print("New List A:", list_3)
print("New List B:", list_4)

What’s in the Box?

import random

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] # prints a random value from the list

correct_guess = random.choice(list1) # random number to be guessed


guess_count = 0
guess_limit = 3

print("Enter Number in range of 1-9 \n You have 3 chances")

# Loop to take input user 3x if not guess the number


while guess_count < guess_limit:
guess = int(input('Input Number: '))
guess_count += 1
if guess > 9:
pass
if guess == correct_guess:
print('Congratulations! You won!')
continue

else:
print('Better Luck Next Time!!')
print("The Number is", correct_guess)

Results and Discussion:

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
54
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

What’s in the Box?

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
55
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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:

GeeksforGeeks (n.d.). Python | continue statement. Retrieved from


https://www.geeksforgeeks.org/python-continue-statement/ JavaTpoint (n.d.).

Python continue statement. Retrieved from https://www.javatpoint.com/python-continue

JavaTpoint (n.d.). Python pass statement. Retrieved from


https://www.javatpoint.com/python-pass-statement PythonPool (n.d.).

Python break statement. Retrieved from https://www.pythonpool.com/python-break/

TutorialsPoint (n.d.). Python3 - continue statement. Retrieved from


https://www.tutorialspoint.com/python3/python_continue_statement.htm

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/

Find All Divisors of an Integer in Python - 4 Lines Code (codespeedy.com). Retrieved


from https://www.codespeedy.com/find-all-divisors-of-an-integer-in-python/

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
56
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 10
Linear Search Algorithm

Objectives:

 To utilize linear search algorithm to solve data-specific problems such as


searching for a specific number in a list of numbers.
 To Implement linear search algorithm in Python using object-oriented
programming principles.

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
57
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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)

# Removes duplicate sample and sort it on list


se = set(lst)
lst = list(se)
remove_dup = random.sample(lst, len(lst))
remove_dup.sort()
print("Here's the generated random numbers:\n", remove_dup)

# Checks the value if in the list


def LinearSearch(input_list: list, element: int):
list_len = len(input_list)
for i in range(list_len):
if input_list[i] == element:
return i
return -1

# Prompt user to choose a number from the list


print("Number of Samples: (n) ", len(remove_dup))
input = int(input("Enter Choose Number: "))

# Prints the index of chosen number


position = LinearSearch(remove_dup, input)

# Calculates the decile value of the input


def decile_value():
index = position + 1
print("Input is at index:", index) # serves as the index at missing decile
#from Dk = K(n/10) to K = Dk(10/n)
K = round(index * (10 / len(remove_dup)))
print("Solution: \n "
"Dk = K(n/10)\n "
" K = Dk(10/n)\n ",
"=",index,"x 10 /",len(remove_dup),
"=", K)
print("Therefore,",input, "is at", number.ordinal(K),"Decile")

# Checks if the input is in the list


if input in remove_dup:
decile_value()

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
58
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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"]

# Shuffle the string list


random.shuffle(choices)
length = len(choices)

# Prompt user to choose letter from A-E


print("PICK A BOX!\n", "BOX: A B C D E \n")
user_input = input(" ")
user_input.upper()
#Checks if user input if in the choices
for value in user_input:
if user_input not in ['A', 'B', 'C', 'D', 'E']:
print('ERROR: Not in the Choices!!')
exit()

# Corresponding index of letters in the list


if user_input == 'A':
new = choices[0]
elif user_input == 'B':
new = choices[1]
elif user_input == 'C':
new = choices[2]
elif user_input == 'D':
new = choices[3]
else:
new = choices[4]

win = "Jackpot"

# Search the “Jackpot” index in the shuffled list


def linear_search(choices, length, win):
for i in range(0, length):
if choices[i] == win:
return i
return -1

# Check if the string associated with the user input is "Jackpot"


if new == win:
print("Congratulations!!!")

# Otherwise, print the index of “Jackpot” within the choices list


else:
print("The Jackpot is at index: ", linear_search(choices, length, win))

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
59
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# Print the string associated with the user input


print(new)

Results and Discussion:

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:

Lambert, K. A. (2019). Fundamentals of Python: Data Structures (2nd ed.). Cengage


Learning.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
60
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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/

Linear search in Python (Simplified Python, n.d.). Retrieved from


https://www.simplifiedpython.net/linear-search-python/

(Gates, P. (n.d.). Linear Search in Python. PythonForBeginners.com. Retrieved from


https://www.pythonforbeginners.com/algorithms/linear-search-in-python;

Javatpoint. (n.d.). Linear Search in Python. Retrieved from


https://www.javatpoint.com/python-linear-search).

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
61
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

LABORATORY REPORT
No. 11
Binary Search Algorithm

Objectives:

 To Understand the concept of binary search and its implementation in Python.


 To optimize the code for time complexity, ensuring it is as efficient as possible in
terms of both speed and memory usage and:
 To develop an algorithm to perform binary search on an array of data.

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

def binary_search(arr, target):


# set the start and end indices for the search
start = 0
end = len(arr) - 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

# check if the target is at the midpoint and return


if arr[mid] == target:
return mid

# check if the target is greater than the midpoint


elif arr[mid] < target:
start = mid + 1

# otherwise, the target must be less than the midpoint


else:
end = mid - 1

# 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

# Test the function


arr = [2, 4, 5, 6, 7, 8]
target = 3

# Search for the target


index = binary_search(arr, target)

# Print out the new array with the added element


print("New list with the added element", target, "\n", arr)

# Print out where the element was added


print("Element added at index:", index)

Code 2

# Creating a list
list_1 = [20, 44, 48, 55, 62, 66, 74, 88, 93, 99]

# Creating a target value


target_value = 90

# Initialize left and right index


COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
63
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

left = 0
right = len(list_1)-1

# Search each part


while left <= right:
midpoint = (left + right)//2
if list_1[midpoint] == target_value:
print("The index of the element is: ", midpoint)
break
elif list_1[midpoint] < target_value:
left = midpoint + 1
else:
right = midpoint - 1

# If the element is not present


if left > right:
print("Element is not present")

Results and Discussion:

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
64
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

References:

SimpliLearn (n.d.). Binary Search Algorithm. Retrieved from


https://www.simplilearn.com/binary-search-algorithm-article

GeeksforGeeks (n.d.). Binary Search. Retrieved from


https://www.geeksforgeeks.org/binary-search/

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/

Binary Search in Python a Simple Practical Explanation. (2020). Teaching Resources.


https://www.tes.com/teaching-resource/binary-search-in-python-a-simple-
practical-explanation-12172599

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
65
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
66
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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 input(self, new_text):


# Save current text to undo stack and add new text with a space at the beginning
# Clear redo stack because new input invalidates previous redos
self.undo_stack.append(self.text)
self.text += " " + new_text
self.redo_stack.clear()

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()

# Initialize TextEditor instance


editor = TextEditor()
print("Welcome to the History-Tracking Text Editor!")
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
67
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

print("Enter text to add it to the document, or enter a command.")

# Continuously prompt user for input


while True:
action = input("Options:\nu = undo r = redo\nc = clear x = exit\n ")

# Execute actions based on user input


if action == "r":
editor.redo()
print("Redo successful.")
elif action == "u":
editor.undo()
print("Undo successful.")
elif action == "c":
editor.clear()
print("Document cleared.")
elif action == "x":
# Exit loop
break
else:
# Assume input is new text to add to document
text = action
editor.input(text)
print("Text added to document.")
# Print current text
print("\nCurrent document:")
print(editor.text)

Stack Organizer

class Stack:
def __init__(self):
self.items = [] # Initialize an empty list to store stack items

def push(self, item):


"""Push an item to the top of the stack."""
self.items.append(item) # Store the input in the list
print(f"{item} pushed to stack")

def pop(self):
"""Pop an item from the top of the stack.

If the stack is empty, print an error message.


"""
if self.items: # Check if the stack is not empty
popped_item = self.items.pop()
print(f"{popped_item} popped from stack")
return popped_item
else:
print("Stack is empty")

def peek(self):
"""Return the top item of the stack without removing it.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
68
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

If the stack is empty, print an error message. """


if self.items: # Check if the stack is not empty
return self.items[-1]
else:
print("Stack is empty")

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")

choice = int(input("\nEnter your choice: "))

if choice == 1: # Push an element to the stack


element = input("\nEnter element to push: ")
stack.push(element)
elif choice == 2: # Pop an element from the stack
stack.pop()
elif choice == 3: # Peek at the top element of the stack
element = stack.peek()
if element:
print(f"\nTop element of the stack: {element}")
elif choice == 4: # Get the size of the stack
print(f"\nSize of stack: {stack.size()}")
elif choice == 5: # Check if the stack is empty
if stack.is_empty():
print("\nStack is empty")
else:
print("\nStack is not empty")
elif choice == 6: # Display the list of inputs
print(f"\nList of inputs: {stack.items}")
elif choice == 0: # Exit the program
break
else: # Invalid choice
print("\nInvalid choice. Try again.")

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

Results and Discussion:


Based-Text-Editor
The goal of 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 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.

def input(self, new_text):


self.undo_stack.append(self.text)
self.text += " " + new_text
self.redo_stack.clear()

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.

def push(self, item):


self.items.append(item)
print(f"{item} pushed to 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")

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
71
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
72
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
73
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
74
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

# Create a Queue class


class Queue:
# Initialize the Queue and assign the items to an empty list
def __init__(self, maxsize=0):
self.items = []
self.maxsize = maxsize

# Check if the Queue is empty


def is_empty(self):
# Return true if the Queue is empty, else return false
return not self.items

# Check if the Queue is full


def is_full(self):
if self.maxsize > 0:
return len(self.items) == self.maxsize
return False

# Add an item to the Queue


def put(self, item):
if self.is_full():
raise QueueFullError
self.items.append(item)

# Remove an item from the Queue


def get(self):
if self.is_empty():
raise QueueEmptyError
return self.items.pop(0)

# Check the size of the Queue


def size(self):
return len(self.items)

# Clear the Queue


def clear(self):
self.items = []

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
75
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

# Create a queue with a maximum size of 11


q = Queue(maxsize=11)

# Enqueue the digits of the number


for digit in number:
q.put(digit)

# 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

# Add the modified number to the list of contact numbers


contact_numbers.append(modified_number)

if __name__ == "__main__":
main()

Customer Queuing System


COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
76
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

from datetime import datetime

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 add(self, customer):


# Add the customer to the queue and print a message
self.queue.append(customer)
print(f'{customer.name} has joined the queue at time {customer.arrival_time}.')

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()

# Print the menu


print('1. Add customer to queue')
print('2. Remove customer from queue')
print('3. Print queue')
print('4. Print removed customers')
print('5. Quit')

# Continuously prompt the user for input until they choose to quit
while True:
# Get the user's choice
choice = input('Enter your choice: ')

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
77
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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()

def receive_shipment(self, item):


# Add the item and zip code to the left side of the deques
self.items.appendleft(item)

def item_zipcode(self, zip_code):


self.zip_codes.appendleft(zip_code)

def ship_item(self, item, destination):


# Check if the item is in the deque
if item not in self.items:
print("Error: The specified item is not in the warehouse.")
else:
# Generate a tracking number for the shipped item
tracking_number = self.generate_tracking_number()
# Add the tracking number to the tracking numbers deque
self.tracking_numbers.appendleft(tracking_number)
# Remove the item and zip code from the deques
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
78
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

self.items.remove(item)
#self.zip_codes.popleft()

print(f"{item} has been shipped to {destination} with tracking number


{tracking_number}.")

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)

# Create a new warehouse


warehouse = Warehouse()

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: ")

# Ship the item


warehouse.ship_item(item, destination)
# Receive the shipment
warehouse.item_zipcode(zip_code)

else:
# Print an error message if the input is invalid
print("Invalid input. Please try again.")

# Print the current

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
79
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# Print the current inventory


print("ITEMS: ",warehouse.check_inventory())

Jigsaw Puzzle

import time
from collections import deque
import random

# Initialize the deque of puzzle pieces


pieces = deque(["A", "B", "C", "D", "E", "F", "G", "H", "I"])
# Shuffle the puzzle pieces
random.shuffle(pieces)

new = pieces
random.shuffle(new)

# Initialize the list of moves


moves = []

# Start the timer


start_time = time.time()

# Print the main menu


print("\nJigsaw Puzzle\n-------------")
print("1. Move piece to front")
print("2. Move piece to back")
print("3. Check completion")
print("4. Quit")
# Main program loop
while True:
# Print the current puzzle state
print("\nCurrent puzzle:", list(pieces))
choice = input("Enter your choice: ")

# Move piece to front


if choice == "1":
piece = input("Enter a puzzle piece to move to the front: ")
if piece in pieces:
# Remove the piece from the deque
pieces.remove(piece)
# Add the piece to the front of the deque
pieces.appendleft(piece)
# Add the move to the list of moves
moves.append(("front", piece))
else:
print("Invalid piece! Please try again.")

# Move piece to back


COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
80
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

elif choice == "2":


piece = input("Enter a puzzle piece to move to the back: ")
if piece in pieces:
# Remove the piece from the deque
pieces.remove(piece)
# Add the piece to the back of the deque
pieces.append(piece)
# Add the move to the list of moves
moves.append(("back", piece))
else:
print("Invalid piece! Please try again.")
# Check completion
elif choice == "3":
if list(pieces) == new:
# Stop the timer
end_time = time.time()
# Calculate the elapsed time
elapsed_time = end_time - start_time
print("\nCongratulations, you have completed the puzzle!")
print("Moves:", moves)
print("Time:", elapsed_time, "seconds")
break
else:
print("\nThe puzzle is not complete. Keep trying!")
print(new)

# Quit the program


elif choice == "4":
break
else:
print("Invalid choice! Please try again.")

Results and Discussion:


QUEUES
Contact Data Base
The given code in Python programming is code is designed to modify the numbers by
changing the leading digit ‘0’ to Philippine country code ‘+63’ and store them in a list of
contact numbers. The code functions by utilizes the Queue class to enqueue and
dequeue the digits of the given numbers, and then adds the modified number to the list
of contact numbers. The code also contains functions to view, clear and exit the
program. By executing the code, the goal of creating a Queue class and storing the
modified contact numbers was achieved. The hypothesis of the code being able to
modify and store the numbers was true, as the results were as expected. The code was
easy to understand, line by line, and the results were as expected. If another method or
equipment was used, the results may vary and would need to be analyzed. The results
correlate with the general theory of this question, as the code was able to successfully
store the modified contact numbers.
Customer Queuing System

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
81
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
82
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
83
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

This concept is important because it demonstrates a recursive algorithm for


traversing a binary tree in postorder format and calculating the total value of all the
nodes. The problem was to traverse a binary tree in postorder format and calculate
the total value of all the nodes. Yes, the product can be used as an independent
program. The methodology used was recursion, as it was the most efficient way to
traverse the binary tree in postorder format. The results show the values of the
nodes in postorder format and the total value of all the nodes. The conclusion is that
recursion is an effective algorithm for traversing a binary tree in postorder format
and calculating the total value of all the nodes.

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):

# Initialize the employee with a name and a performance rating


self.name = name
self.performance_rating = performance_rating

# Initialize left and right children to None


self.left = None
self.right = None

def preOrder(tree, counter =1):


if tree:
# Prints the employee name and performance rating
print(f"Employee {counter}: {tree.name}")
print(f"Performance rating: {tree.performance_rating}")

# Traverse left subtree


preOrder(tree.left, 2 * counter)

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
85
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# Traverse right subtree


preOrder(tree.right, 2 * counter + 1)

# 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)

# Print preorder traversal of employee performance


print("Preorder traversal of employee performance is")
preOrder(root)

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

def preOrder(tree, counter=1):


# Function that performs preorder traversal of the tree
if tree:
# Print the current node data
print(f"Node {counter}: {tree.data}")

# Traverse left and right subtree


preOrder(tree.left, 2*counter)
preOrder(tree.right, 2*counter + 1)

def updateNode(tree, counter, data):


# Function to update a node in the tree
if tree:
# If the current node is the one we want to update, set its data to the new value
if counter == 1:
print(f"Updating Node {counter} with {data}")
tree.data = data
return
# Otherwise, traverse left or right subtree
elif counter % 2 == 0:
updateNode(tree.left, counter//2, data)
else:
updateNode(tree.right, counter//2, data)

# 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()

# Print the tree in preorder traversal


print("Original tree:")
preOrder(root)

# Get user input for node to update and new value


while True:
counter = int(input("Enter node to update (1-7): "))
if counter not in range(1, 8):
print("Please enter a valid node (1-7)")
continue
else:
break
data = int(input("Enter new value for node: "))

# Update the node


updateNode(root, counter, data)

# Print the tree in preorder traversal again


print("\nUpdated tree:")
preOrder(root)

INORDER TRAVERSAL
Tree Pruning

import random

#Create a class called Node to store data and a name


class Node:
def __init__(self, data, name):
self.data = data
self.name = name
self.left = None
self.right = None

#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 = []

#set the left and right children to None


root.left = None
root.right = None
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
87
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

else:
#call the function recursively for the left and right children
removeBranch(root.left, node_name)
removeBranch(root.right, node_name)

#Function to print the data in an in-order traversal


def inOrderTraversal(root):
#if the root exists and the data is not None
if root and root.data:
#call the function recursively for the left & right child
inOrderTraversal(root.left)
#print the name and data
print(f"{root.name}: {root.data}")
inOrderTraversal(root.right)

#Function to create a list of node names in an in-order traversal


def inOrderTraversalWithoutData(root, node_list=[]):
#if the root exists
if root:
#call the function recursively for the left and right child
inOrderTraversalWithoutData(root.left, node_list)
node_list.append(root.name) #add the node name to the node list
inOrderTraversalWithoutData(root.right, node_list)

return node_list

#Create the root node with the given data and name
root = Node(random.sample(range(1, 30), 7), "A")

root.left = Node(random.sample(range(1, 30), 7), "B")


root.right = Node(random.sample(range(1, 30), 7), "C")

root.left.left = Node(random.sample(range(1, 30), 7), "D")


root.left.right = Node(random.sample(range(1, 30), 7), "E")

root.right.left = Node(random.sample(range(1, 30), 7), "F")


root.right.right = Node(random.sample(range(1, 30), 7), "G")

root.left.left.left = Node(random.sample(range(1, 30), 7), "H")

#Print the list of node names in an in-order traversal


print("In-ordered Traversal:", inOrderTraversalWithoutData(root, node_list=[]))
inOrderTraversal(root)

node_name = input("Please enter the name of the node to remove: ")

#Call the removeBranch function to remove the branch with the given name
removeBranch(root, node_name)

#Print updated tree


print("\nAfter removing node")
inOrderTraversal(root)

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 Node class to hold the information of each family member


class Node:
def __init__(self, name, lastname):
self.name = name
self.lastname = lastname
self.left = None
self.right = None

# Define a Tree class to define the family tree


class Tree:
def __init__(self):
self.root = None

# Define a function to add a node to the tree


def addNode(self, name, lastname):
newNode = Node(name, lastname)
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

# 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)

# Create a new tree


tree = Tree()

# Add some nodes to the tree


tree.addNode('John', 'Smith')
tree.addNode('Nancy', 'Jones')
tree.addNode('Peter', 'Brown')
tree.addNode('Molly', 'Anderson')

# Print out the family tree before arrangement


print("Before Arrangement:")
print("John Smith")
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
89
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

print("Nancy Jones")
print("Peter Brown")
print("Molly Anderson")

# Print out the family tree in alphabetical order by last name


print("\nAfter Arrangement:")
tree.printTree(tree.root)

POSTORDER TRAVERSAL
Node Calculation

class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value

def postorderTraversal(root, total=0):


# If the root node exists, perform postorder traversal
if root:
# Visit left & right child and update total value
total = postorderTraversal(root.left, total)
total = postorderTraversal(root.right, total)

# 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:
")))

# Print message indicating postorder traversal format


print("Postorder Traversal Format")

# Perform postorder traversal and calculate total value of all nodes


total = postorderTraversal(root)

# Print total value of all nodes


print("\nSum of all node values: ", total)

Room In use

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
90
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

import time

# Create Room class


class Room:
# Create an initializer method
def __init__(self, number, duration=0):
# Set the number and duration of the room
self.number = number
self.duration = duration

# Set the left and right attribute for the room


self.left = None
self.right = None

# Create post order traversal function


def postorder_traversal(room, schedule):
# If the room's left attribute is not null
if room.left:
# Call postorder_traversal on the left attribute
postorder_traversal(room.left, schedule)
# If the room's right attribute is not null
if room.right:
# Call postorder_traversal on the right attribute
postorder_traversal(room.right, schedule)
# If the duration of the room is equal to 0
if room.duration == 0:
# Set the schedule for the room to AVAILABLE
schedule[room.number] = "AVAILABLE"
else:
# Set the schedule for the room to IN USE with the remaining seconds
schedule[room.number] = f"IN USE ({room.duration} seconds remaining)"

# Create create schedule function


def create_schedule(rooms):
# Create an empty schedule dictionary strong value of time
schedule = {}

# Iterate through the rooms


for room in rooms:
# If the duration of the room is greater than 0 (countdown part)
if room.duration > 0:
room.left = Room(room.number, room.duration - 1)
room.right = Room(room.number)
room.duration -= 1
else:
# Set the left & right attribute of the room to None
room.left = None
room.right = None

# Call postorder_traversal on the room


postorder_traversal(room, schedule)
# Return the schedule
return schedule

# Create input rooms function


COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
91
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

# Ask the user to enter the duration for the room


duration = int(input(f"Enter the duration for room {number} (in seconds): "))
room = Room(number, duration)
rooms.append(room)
return rooms

print("Welcome to the Room Scheduler!")


# Call input_rooms and assign the returned list to rooms
rooms = input_rooms()

# Create an infinite loop


while True:
# Sleep for 1 second
time.sleep(1)

# Call create_schedule and assign the returned dictionary to schedule


schedule = create_schedule(rooms)
print("\nRoom Schedule:")

# Iterate through the schedule


for number, availability in schedule.items():
# Print the availability of each room
print(f"Room {number}: {availability}")

# If all of the rooms have a duration of 0 loop will stop


if all(room.duration == 0 for room in rooms):
break

# Print an exit message


print("Both rooms are now available. Exiting program.")

Results and Discussion:


PREORDER TRAVERSAL
Employee Performance

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.

def preOrder(tree, counter =1):


if tree:
# Prints the employee name and performance rating
print(f"Employee {counter}: {tree.name}")
print(f"Performance rating: {tree.performance_rating}")

# Traverse left subtree


preOrder(tree.left, 2 * counter)

# Traverse right subtree


preOrder(tree.right, 2 * counter + 1)

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)

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
93
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

Then a ‘preOrder(tree, counter=1)’ function is define, which which performs a pre-order


traversal of the tree. The function takes the root of the tree and an optional counter
parameter, which is used to label the nodes as they are printed. The function uses
recursion to traverse the tree, first visiting the root node, then the left subtree, and finally
the right subtree. The current node's data and counter are printed before each recursive
call.

def preOrder(tree, counter=1):


if tree:
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
94
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

print(f"Node {counter}: {tree.data}")

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.

def updateNode(tree, counter, data):


if tree:
if counter == 1:
print(f"Updating Node {counter} with {data}")
tree.data = data
return
elif counter % 2 == 0:
updateNode(tree.left, counter//2, data)
else:
updateNode(tree.right, counter//2, data)

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()

# Print the tree in preorder traversal


print("Original tree:")
preOrder(root)

# Get user input for node to update and new value


while True:
counter = int(input("Enter node to update (1-7): "))
if counter not in range(1, 8):
print("Please enter a valid node (1-7)")
continue
else:
break
COLLEGE OF ENGINEERING AND ARCHITECTURE
COMPUTER ENGINEERING DEPARTMENT
95
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

data = int(input("Enter new value for node: "))

# Update the node


updateNode(root, counter, data)

# Print the tree in preorder traversal again


print("\nUpdated tree:")
preOrder(root)

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
96
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

def removeBranch(root, node_name):


if root:
if root.name == node_name:
root.data = []
root.left = None
root.right = None
else:
removeBranch(root.left, node_name)
removeBranch(root.right, node_name)

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)

I also created a function inOrderTraversalWithoutData to traverse the tree in an in-order


manner and create a list of the node names. This function will traverse the left subtree,
add the node's name to the list, and then traverse the right subtree.

def inOrderTraversalWithoutData(root, node_list=[]):

if root:

inOrderTraversalWithoutData(root.left, node_list)
node_list.append(root.name)
inOrderTraversalWithoutData(root.right, node_list)

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
97
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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

root = Node(random.sample(range(1, 30), 7), "A")

root.left = Node(random.sample(range(1, 30), 7), "B")


root.right = Node(random.sample(range(1, 30), 7), "C")

root.left.left = Node(random.sample(range(1, 30), 7), "D")


root.left.right = Node(random.sample(range(1, 30), 7), "E")

root.right.left = Node(random.sample(range(1, 30), 7), "F")


root.right.right = Node(random.sample(range(1, 30), 7), "G")

root.left.left.left = Node(random.sample(range(1, 30), 7), "H")

print("In-ordered Traversal:", inOrderTraversalWithoutData(root, node_list=[]))


inOrderTraversal(root)

node_name = input("Please enter the name of the node to remove: ")

print("\nAfter removing node")


inOrderTraversal(root)

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

After removing node


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]

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.

def addNode(self, name, lastname):


newNode = Node(name, lastname)

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
99
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

def printTree(self, node):


if node is not None:
self.printTree(node.left)
print(node.name + " " + node.lastname)
self.printTree(node.right)

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

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
100
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

def postorderTraversal(root, total=0):


if root:
total = postorderTraversal(root.left, total)
total = postorderTraversal(root.right, total)

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:
")))

print("Postorder Traversal Format")

total = postorderTraversal(root)

print("\nSum of all node values: ", total)

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
101
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

Output:

Enter value for root node: 1


Enter value for left child of root: 2
Enter value for right child of root: 4
Enter value for left child of left child of root: 5
Enter value for right child of left child of root: 8
Enter value for left child of right child of root: 7
Enter value for right child of right child of root: 3
Postorder Traversal Format
5827341
Sum of all node values: 30

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:

def __init__(self, number, duration=0):

self.number = number
self.duration = duration

self.left = None
self.right = None

Then, a "postorder_traversal" functions is created which takes in two arguments: a


"room" object and a "schedule" dictionary. The function utilizes a postorder traversal
method to iterate through the "room" object and its attributes (left and right). It will then
check if the “room” object’s “left” attribute is not null. If it is not, the function calls itself
recursively and passes in “left” attribute as the new "room" argument and the "schedule"
dictionary. This continues until the function reaches a "left" attribute that is null. Once
the function has reached the end of the "left" and "right" attributes, it checks if the
"duration" attribute of the "room" object is equal to 0. If it is, the function sets the

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
102
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

"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.

def postorder_traversal(room, schedule):

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

if any(x.number == number for x in rooms):


print("Error: Room is already in use.")
continue

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:")

for number, availability in schedule.items():

print(f"Room {number}: {availability}")

if all(room.duration == 0 for room in rooms):


break

print("Both rooms are now available. Exiting program.")

Output:

Welcome to the Room Scheduler!


Enter the number of the room (or enter to finish): 1
Enter the duration for room 1 (in seconds): 2
Enter the number of the room (or enter to finish): 2
Enter the duration for room 2 (in seconds): 3
Enter the number of the room (or enter to finish):

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:

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
104
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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.

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
105
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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")

# Prompt the user to enter a command


command = input("Enter a command: ")
if command.upper() == "A":

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
106
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

# 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()

# Use a negative value for time_until_event to create a max heap


heapq.heappush(events, (-time_until_event, event))

elif command.upper() == "D":


# If the user wants to delete an event, prompt them to enter the event index
if not events:
print("No events to delete.")
else:
index = int(input("Enter the index of the event to delete (0-based): "))
if index < 0 or index >= len(events):
print("Invalid index.")
else:

# 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

elif command.upper() == "L":


# If the user wants to list the events, print them
if not events:
print("No events scheduled.")
else:
print("Events:")

for i, (time, event) in enumerate(events):


# Use a negative value for time to convert it back to its original value
event_time = datetime.now() + timedelta(seconds=-time)
print(f"{i}: {event} on {event_time.strftime('%Y-%m-%d %H:%M')}")

elif command.upper() == "Q":


# If the user wants to quit, end the program
break
else:
print("Invalid command. Please try again.")

# Test the program


event_scheduler()

Transaction Tracker

import heapq

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
107
LABORATORY REPORTS IN DATA STRUCTURES AND ALGORITHMS
ENGR. JAY-AR M. PENTECOSTES

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":

# If it's an expense, add it to the expenses heap


amount = float(input("Enter the amount of the expense: "))
description = input("Enter a description of the expense: ")
heapq.heappush(expenses, (amount, description))

elif type_.upper() == "I":

# If it's an income, add it to the income heap


amount = float(input("Enter the amount of the income: "))
source = input("Enter the source of the income: ")
heapq.heappush(income, (amount, source))

elif type_.upper() == "Q":


# If the user wants to quit, end the program
break
else:
print("Invalid input. Please try again.")

# Calculate the total expenses and income


total_expenses = sum(amount for amount, _ in expenses)
total_income = sum(amount for amount, _ in income)

# Calculate the balance (income - expenses)


balance = total_income - total_expenses

# Print the summary


print("\nSummary:")
print(f"Total expenses: {total_expenses}")
print("Expenses:")

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

# Test the program


budget_management()

Results and Discussion:


Note your Event
This code is used to create an event scheduler. To begin, an empty max heap is
initialized to store the events. The user is then given the options of adding an event,
deleting an event, listing the events, or quitting the program. When the user selects
"Add event", they are prompted to enter the event details, including the event name and
date and time. This is then used to calculate the time until the event, and a negative
value of this is used to create a max heap. When the user selects "Delete event", they
are prompted to enter the index of the event they want to delete, and the max heap is
converted to a list and the event is deleted. When the user selects "List events", the
max heap is converted to a list and the events and dates are printed. Finally, if the user
selects "Quit", the program ends. My hypothesis that this code will be able to create an
event scheduler was true, as it was able to successfully run and perform the given
functions. Additionally, if a different method or equipment was used, the results could
have been similar, depending on the method or equipment. The results correlate with
general theory, as the code successfully created an event scheduler, which is the
general theory of this code.
Transaction Tracker
The code above is a program designed to help with budget management. The program
starts by prompting the user to enter a transaction, either an expense or an income. The
user is asked to enter a type, amount, and description or source of the transaction. The
values are then stored in either a min heap for expenses or a max heap for income. The
total expenses and income are calculated, as is the balance of the two. The summary of
the transactions is printed out. This code is an efficient way to manage a budget, as it
stores the data in the heaps and quickly calculates the total expenses, income, and
balance. If a different method or equipment were used, the data would still be stored
and calculated, but it may take longer to do so. The results of this code are in line with
the general theory of budget management, as it accurately stores and calculates the
data.

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)

COLLEGE OF ENGINEERING AND ARCHITECTURE


COMPUTER ENGINEERING DEPARTMENT
109

You might also like