0% found this document useful (0 votes)
2 views87 pages

Itcds Manual f23

Uploaded by

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

Itcds Manual f23

Uploaded by

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

INTRODUCTION TO COMPUTING

AND DATA SCIENCE


Lab Manual

Rehan Naeem
[email protected]
1

TABLE OF CONTENTS
TABLE OF CONTENTS ......................................................................................................................................... 1
Lab Outline ............................................................................................................................................................ 2
Rubrics ................................................................................................................................................................... 4
Lab1: Implementation of PRINT Statement and Arithmetic Operations in PYTHON .................................... 5
Lab2: Implementation of Functions, Comparison and Logical Operators in Python................................. 10
Lab 3: Implementation of Conditional Statements & Lambda Functions in Python .................................. 15
Lab 4: Implementation of Non-Nested Loops and Strings in Python ........................................................... 20
Lab 5: Implementation of Nested Loops and Function Scope in Python .................................................... 30
Lab 6: Implementation of Higher Order Functions in Python ....................................................................... 34
Lab 7: Implementation of 1D and 2D Lists in Python ..................................................................................... 41
Lab 8: Implementation of Recursion in Python .............................................................................................. 46
Lab 12: Dictionaries and Exception Handling in Python ............................................................................... 49
Lab 9: Implementation of Object-Oriented Programming in Python ............................................................ 54
Lab 10: Plotting Data in Python ........................................................................................................................ 65
Lab 13: Data Science using Python.................................................................................................................. 70
Lab 14: Signal Manipulation & Processing in Python .................................................................................... 77

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
2

Lab Outline

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
3

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
4

Rubrics
Assessment Type Weightage CLOs Marks Criteria

0 Absent or the program file is empty, or the question not


attempted, or the program file is missing/not
submitted.

1 Code written but output does not appear, or error


message is displayed, or hard coding was
implemented.

2 Code written and output appears, but output is 100%


incorrect or percentage of the output being correct <
Percentage of the output being incorrect. programs
CLO 1, and 2 were not separated by #%.

Evaluations 80 3 Code runs successfully and no error message is


displayed and percentage of the output being correct
> Percentage of the output being incorrect. Also
Percentage correctness < 98%

4 Code runs successfully and no error message is


displayed and percentage of the output being correct
is in the range 98% to 99%

5 Output is 100% correct.

2 Answered questions honestly without using unfair


CLO 3
means.

2 Good programming practices like indentation, use of


CLO 4
spaces followed.

0 Incorrectly answered 100% of the questions asked /


Absent.

2 Correctly answered 10% - 40% of the questions asked


CLO 1, and 2
15 3 Correctly answered 50% - 70% of the questions asked

Viva 4 Correctly answered 80% - 90% of the questions asked

5 Correctly answered 100% of the questions asked

2 Answered questions honestly without using unfair


CLO 3
means.

2 Used easy to understand words and an effective


CLO 4
method for answering

Attendance CLO 3
5 Attendance > 75% / Came to lab on time

5 0 Attendance < 75% / Came to the lab late.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
5

Lab1: Implementation of PRINT Statement and


Arithmetic Operations in PYTHON
Things to be covered in this experiment:
● Introduction to SPYDER software
● PRINT statement and f-strings
● Use of \n and end=””
● Debugger and flowcharts
● Implementing basic arithmetic & trigonometric operations

Recommended To DOs: Watch this video to know the procedure to download and install SPYDER
software. You can also watch my lecture here related to experiment 1. Note: This video might not
cover all the concepts required for completing experiment 1. So, coming to the lab is a must. If
you want to know about any operator, function, syntax, libraries etc related to PYTHON, then
visit https://docs.python.org/3/library/index.html and please avoid other websites.

Guidance to Write, Save and Submit codes


• Create a new file and write codes for all questions in that single file.
• Type #%% at the start of the code for each question to separate the codes.
• Save the file using the name “Lx.py” where x is the experiment number. For example “L1.py” for
experiment 1.
• You will be asked to submit the “L1.py” file. Procedure to submit will be shared.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
6

Non availabitity of computer:

If you dont have a laptop or desktop or unable to practice in the lab, you can use smartphone for the
time being. In your smartphone use the following link to write python code.
https://pythontutor.com/

1. Determine the output of the following program without using the computer.
a. Sequential Code Execution: Use a pencil and a page to write the output of the program
shown in the table below. Note the two ways used to print; one using simple print statement
(line#70), the other using f-string (line#72 and 75). What will be the output if instruction at
line 71 and 73 are swapped? You will see that the output will be different but not always as
you will see in question 5.
b. SPYDER Debugger: Copy/paste the code below available here into the SPYDER. Use
debugger of the SPYDER software to execute each line of the code one by one. Observe the
values of x and y stored when each line is executed.
c. Environment Diagram in Python Tutor: Copy/paste the following code into the python
tutor website. Execute each line of the code one by one. After executing each line of the code,
you will see some things appear below the word “Frames” and/or “Objects” shown in fig. 2.
Write down those things in your notebook after executing each line. We will be using python
tutor extensively in future experiments, especially to understand the working of Higher-
Order Functions
Code: Output:

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
7

2. Finding & Eliminating Syntax Errors: Paste the following code into the SPYDER IDE.
A. When you run the code, you get the Syntax Error message shown below. The first two lines
indicate the location in your computer where the code file is stored. Go to that location and see
if the code file is present or not.
B. Line number 79 indicates the location where there is a mistake in the code. Correct the mistake
and run the code again. What message did you get at the output console? Any mistake left to be
corrected? Eliminate all the errors in the code to get the output in the console window as shown
below. Write the correct code and run it.
Code: Required Output:

Actual Output after one correction

3. Print and Flowchart: Write a program that prints the message as shown below. Use multiple print
statements to get the output. Draw a flowchart for this program. A flowchart is a pictorial
representation of an algorithm. More on algorithms will be shared later in lab 3.

Output

4. Printing Diamonds: Write a program to print the diamond as shown below.

a. Use multiple print statements to complete the task.


b. Use one print statement to complete the task.
Note: Pay attention to the number of rows, the number of asterisks (*), the position of asterisks
(*) and the number of spaces before (*) in each row.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
8

Output

5. Basic Arithmetic Operations: Write a program that calculates and displays the roots of a quadratic
equation 3𝑥 2 + 𝑥 − 2. For this purpose, convert the flow chart below to a PYTHON code. The
formula to calculate the roots is given below.

Flow Chart Formula

Output

1. Will the output change if the positions of the 1st and 2nd blocks are swapped?
2. What will be the output of the program if the positions of the1 st and last blocks are swapped?
Notice that the coefficients of the quadratic equation were stored in variables a, b and c in the code. The
code works correctly for any values of a, b and c. This code is said to be a generalized code. In the code, we
can do away with these variables and write the coefficients directly in the expression.
Prepared By: Rehan Naeem
Formatted By Khushbakht
Department of Electrical Engineering
9

This type of coding is called hard coding and avoid it specially in the exams.

6. Trigonometric Operations: A right-angle triangle having A = 50 meters and C = 10 meters is shown below.
Write a program to find angle 𝝰 and the side B using the two equations given below. The program should
work correctly for any values of 𝝰 and B. The output should be as shown below.

Formula Diagram

Output

7. Trigonometry: Write a program to evaluate the following expression when a=10, b=5, c=15,
d=20 and 𝜭 = 45°. The program should work correctly for any values of the variables. The output
should be as shown below.

Formula Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
10

Lab2: Implementation of Functions, Comparison


and Logical Operators in Python
Things to be covered in this experiment.
• Logical Operators
• Functions
• Prompting the User
• Environmental Diagrams
Recommended To DOs: You can watch my lecture here related to experiment 2. Note: This video might
not cover all the concepts required for completing the experiment. So, coming to the lab is a must.
For today’s lab, use a single expression containing comparison and/or logical operators inside a single print
instruction to solve question 1 to 5. Don’t use IF-ELSE or any other conditional statement. You are not
required to take input from the user in question 3 to 5. Test your code thoroughly to avoid incorrect output for
certain inputs.

Fall 2024: Do questions 1 to 6, 8, 9 (part a) for the time being.


1. Determining the output: Determine and write the output of the following, in your register, without using
the computer. Also give reason(s).
Code 1 Code 2 Code 3

Code 4 Code 5

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
11

2. A. Prompting and Logical Comparison: Prompt the user to enter marks (only integers) of two subjects
i.e., Math and Urdu. The program should print True if marks in math are greater than or equal to 5 and
marks in Urdu are less than 3 otherwise False should be printed at the output.

Output

B. Testing the Code: You are asked to thoroughly test the code you wrote in part A. For this purpose,
certain Math and Urdu marks can be selected and used in combination. Determine the number of
combinations required to test the code thoroughly. Draw two columns “Math marks” and “Urdu Marks”
on a page and write down the possible combinations i.e., the marks.

3. Prompting and String Comparison: Write a program which prints True if the password entered by
the user matches otherwise False should be printed at the output. Store a password in a variable and
compare it with the password entered by the user. The password can contain digits, uppercase and
lowercase letters, and special characters.

Output

4. Determining the Data Type: Write a program which stores a number into a variable x. The number could
be an integer or a floating-point number. The program should print the answer is True if the number is
an integer otherwise print the answer is False at the output. Note: Use f-string in the print statement
to print the output.

Output 1

Output 2

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
12

5. Floating Number Comparison: Determine the output of the following program. Now type the code and
check the output. Are the expected and actual outputs same? Exact reason of the output will be known
when you will study Digital System Design or Computer Architecture course in the future.
a. Use debugger of the SPYDER software or PYTHON TUTOR website (it is recommended to use
both, as each has some pros and cons) to determine the actual value stored in s. What is the value?
b. Sometimes the number of variables in a code becomes so large that it becomes difficult to keep
track of their values while the code is being debugged using the debugger. In such a case, print
statement can be used to print the current value of the variable. Now, exit the debugging mode,
write a print statement in the code below and run the code to print the value of s at the output
console.
Code

6. Boolean Statements: Abdullah is happy when he gets a WhatsApp message from either Ali or Umar and
not from Salman. Complete the following program that prints True when Abdullah is happy and False
otherwise. Use Boolean value True to indicate Ali, Umar, or Salman sending the message and False
otherwise.
Code

Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
13

7. Built-In Functions: Draw, on a piece of paper, the Environment Diagram for the following code. Also
determine and write its output, in your register, without using the computer. Note: min and max are built-
in functions to find minimum and maximum value in a set of numbers.
Code

8. User-Defined Function (No Argument, No Return Value): Write a function foo( ) which doesn’t take
any parameter / argument and prints the following text at the output. Note: The text enclosed by three
double (or single) quotation marks on either side at line 50-52 is called a docstring. Can you explain the
difference between a comment and a docstring? Discuss with your instructor.
Code Output

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
14

9. A. User-
Defined
Function
(With
Integer

Arguments & Floating-Point Return Values): Write a function CalculateRoots() which calculates the
roots of a quadratic equation 𝟑𝒙𝟐 + 𝒙 − 𝟐 = 𝟎 and returns both the roots (Use one return
statement only) when the function is called. Your code should then print both the roots at the output.
Note: the text preceded by # at line 15 and 16. They are called “comments” and are not executed by
the computer.

Output

B. Diagram: Draw and properly label the Environment Diagram for the above code on a piece of paper,
without using the computer.

Karel:
Chapter1: https://compedu.stanford.edu/karel-reader/docs/python/en/chapter1.html
Chapter2: https://compedu.stanford.edu/karel-reader/docs/python/en/chapter2.html
Chapter3: https://compedu.stanford.edu/karel-reader/docs/python/en/chapter3.html

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
15

Lab 3: Implementation of Conditional


Statements & Lambda Functions in Python
Things to be covered in this experiment.
• Conditional Statements
• Lambda Functions
• Debugging
• Functions with Boolean Arguments
Recommended To DOs: You can watch my lecture here related to experiment 3. This video might not
cover all the concepts required for completing the experiment. So, coming to the lab is a must.
Note: Note: Draw a flowchart before coding question number 4 and 5. Don't
prompt the user for any input in question 4 to 7.

Note: Skip Q1 code 4, and Q6.


1. Determining the Output: Determine the output of the following codes without using a computer.
What is the value of x when Code 1 and 2 run completely? Use debugger to see the flow of the
execution of all the codes below. For what values of c and d the value 6 is returned by xk() in code?
2?
Code 1 Code 2 Code 3 Code 4

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
16

2. Errors: Eliminate all the syntax errors in the following code that displays “The number is even” or
“The number is odd” if x is even or odd respectively.

Code Output

3. Do Q2, 3 and 4 of experiment 2 using branch statements i.e. if, or if-elif or if-elif-else.
4. Writing program using Pseudo-code: Implement the following recipe (algorithm) to find the
grade of a student. The algorithm is described by the text and by the flowchart below. Test your
program to determine whether it works well for all x ≥ 0.
a. Prompt the user to enter the marks and store it in variable x. The marks can be a floating-
point number.
b. If x is greater than 15 then display “The Grade is A”
c. If x is less than equal to 15 and greater than 10 then display “The Grade is B”.
d. If x does not satisfy any of the above-mentioned conditions, then print “Invalid Input.”

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
17
Flow Chart
The output should look exactly like the Case
1,2,3 shown below for different inputs of marks.
Test Case 1

Test Case 2

Test Case 3

5. Function (One Real Number Argument, No Return Value):


A. In the following code, write a function absolute(y) that takes a number as an argument,
calculates the absolute value, and prints it at the output. The program should work correctly for
any number entered by the user. Don't use the built-in function abs(). Hint: Absolute converts a
negative number to a positive number while it does no harm to a positive number. How will you
instruct the computer to convert a negative number to a positive one?
>>Try This Approach: To write functions, I first prefer to write the code without the function
and test it thoroughly. Then I copy & paste that code (The only task the students are good at)
into the function body and do some minor changes to make the function and overall code work
correctly.
Code 1

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
18

Test Case 1: Output when Test Case 1: Output when Test Case 1: Output when
absolute(-1.5) is called absolute(0) is called absolute(8) is called

6. Lambda Function & Tuples: Write a lambda function which takes two arguments x and y and
returns their sum and difference. The sum and difference will be packaged into a Tuple. See code 2
for more details. Draw Environment Diagram for code 2 after you write it completely.
Code 2

Output for x = 2 and y = 3

7. Function (One Real Number Argument, String Return Value): Write a function foo(x) which
returns the string “positive” if the number x is positive, the string “zero” if the number x is a 0 and
the string “negative” if the number x is negative.

8. Debugging the Code: The code below determines and prints the type and values of roots of a
quadratic equation using discriminant (disc). The expected and actual outputs of the code are
shown below. Both outputs are not the same. Your task is to use SPYDER’s debugger and print
statement to debug and correct the code. Identify the errors. Are the errors logical or syntax? Copy
the code from this file and paste it into your code file.
A. Debugger for Debugging: Go into the debugging mode in SPYDER and execute each line of the
code one at a time.
• Observe the variable values in the variable explorer window and compare them with the
values you expect. Modify the instruction in the code which does not work according to
the expectation. Which lines, in the code, do you expect to be executed and which lines
are actually executed and why?

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
19

Using debugger, to observe variable values during debugging, becomes a problem when

number of variables in the variable explorer window is too large and hence becomes
difficult to keep track of them especially when loops are involved.
B. print for Debugging:
• Instead of using debugger to identify the problematic instruction(s), use print
statement(s) at appropriate place(s) in the code to monitor the values of the variables.
If the value of the variable is not according to expectation, then modify the instruction(s)
producing that value.
• Also use print statement(s) at appropriate place(s) in the code to determine whether the
body of the if, elif or else statements got executed or not. The print statements you use
should display such a message which enables you to know which part of the program got
executed. For example: you could write print(“if body got executed”) in the body of the
if statement in code 2. If you run the code and see the message “if body got executed” at
the output window it means the code executed the if statement. How many print
instructions will you use and where will you write them in the code and why?
• In this task, you used print statements to monitor values of the variables and to
determine the flow of the code. Use this handy technique in future for debugging codes,
especially those having logical errors.

Code

Actual Output

Expected Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
20

9. Function with String and Boolean Arguments: Write a function r() which takes three arguments.
The first argument x is the Logical operation (consider AND and NAND operations only) while the
rest of the two arguments y and z are the Boolean operands True or False on which the Boolean
operation is to be applied. The function r() should return Boolean True or False depending on
Boolean operation x. which should then be printed at the output.
Code

Test Case 1: Output when r(“and”, True, Test Case 2: Output when r(“Nand”,
True ) is called True, True ) is called

Lab 4: Implementation of Non-Nested Loops and


Strings in Python
Things to be covered in this experiment.
• Comparison and Logical Operators
• User defined Functions
• Iteration over strings
Recommended To DOs: You can watch my lecture here related to experiment 4. This video might not
cover all the concepts required for completing the experiment. So, coming to the lab is a must.

1. What is printed when you call f(3, 6) in the following code? Give answers on a piece of paper.

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
21

A. Is it possible to call f on a pair of valid arguments such that it only prints ” - - -” to the console? If
yes, give an example pair of arguments and generalize your answer. If not, explain why not.
B. Is it possible to call f on a pair of valid arguments such that the call gets stuck in an infinite loop? If
yes, give an example pair of arguments and generalize your answer. If not, explain why not.

2. Determine the output of the following codes without using the computer.
• Fill the table below while finding the output of code 1. Enter values for all the columns after
running the loop completely.
• Will variable t be modified after line 30 is executed? If not, then modify the code such that
the variable t contains the string ‘Go-1-Tenx’.
• Will line 132 and 133 run? If not, why?
• What will be the output of code 2 if x, y, z = 2, 10, 4?
• What will be the output of code 2 if x, y, z = 12, 10, 4?
• What will be the output of code 2 if x, y, z = 2, 10, -4?
• What does the function mystery() do in code 3 ? Give answers on a piece of paper.

Code 1 Code 2: Modifying range Code 3


parameters

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
22

Table for Code 1


Output X Y

3. Eliminating Errors: Eliminate all the syntax and logical errors in the following code that asks the
user for the number of times “Hello World” is to be displayed and then displays it. Hint: What
number of times the while loop should run? Use for-loop to implement the above task. Draw flow
charts for both the codes.
Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
23

Test Case 1

Test Case 2

Test Case 3

4. Printing multiple times using function: Write a function f() which prints a name ‘n’ times.
Follow steps A, B and C to get the required output.
A. Write a code using for-loop to print “ali” 5 times. Store 5 in variable n. Test the code. If there is
any error, debug it to find and eliminate the error.
B. Now place the code you wrote in part A inside the body of the function f() shown in the code below
and modify it (which requires some thinking now) so that ‘name’ is printed ‘n’ times. For example,
f(“ali”, 3) should print ‘ali’ 3 times. Another example: f(“yahya”, 10) should print yahya 10 times.
Test the code. If there is any error, debug it to find and eliminate the error.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
24

Code

Test case 1: The Test case 2: The


following output comes following output comes
when f(“ail” , 5) is when f(“Parrot”,3) is
called. called.

Notice how we approached this problem of writing a complete function. In part A, you wrote and tested
the code without using user-defined function. Then we wrote the code of part A inside the function f() (Part
B). Follow this approach for writing functions!!!

5. Use of functions to get the desired output: Write a function print even(n) that prints first ‘n’
integers that are even and divisible by 6. The function should also display the number of such
integers. To solve this problem, breakdown this complex problem into simpler problems (Parts A,
B, C and D below) and gradually modify them as required.
A. Write a code to print the first 5 integers including 0 using a for loop.

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
25

B. Now write a function print even(n) which when called should print first ‘n’ integers including 0.
For example, print even(5) should give the following output.
Test case 1: The
following output comes
when print even(5) is
called.

C. Now modify the definition of the function print even() in part B so that it prints integers that are
even and divisible by 6. For example, when print even(50) is called, the following output should
appear.
Test case 1: The
following output comes
when print even(50) is
called.

D. Now modify the function print even() in part B so that it also prints the number of integers that
are even and divisible by 3. For example, when print even(50) is called, the following output
should appear.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
26

Test case 1: The Test case 2: The following output


following output comes comes when print even(30) is
when print even(50) is called.
called.

Notice how we approached this problem by first solving the simplest version of it (Part A) and
then gradually increasing its complexity to get the required output!!! You should also use this
approach to write complex programs. Of course, before writing a program you should know its
algorithm first!

6. Completing the code: Complete and then place the whole code inside the function baz() which
when called should display the output shown below. The function baz() should neither take any
argument nor return anything.

Code Output

7. Prompting the user to get the desired output: Write a program that prompts the user to enter
a number and then that number is displayed at the output as it is. The program should continue to
prompt the user and display the number if the number is less than 5. The program should print
“end” and then stop when the user enters any number greater than 5. Can a loop be used to solve
Prepared By: Rehan Naeem
Formatted By Khushbakht
Department of Electrical Engineering
27

this problem? If so, which loop will you prefer, for or while? Give reasons. Don't write any user-defined
function to solve this problem.

Test Case 1

Test Case 2

8. Iterating Over a String: Write a function foo(x) to determine and return the number of 1s, 2s and
3s in the number x. The program should work correctly for any number containing only the
digits 1, 2 and 3. The output should look like as shown below. Follow the steps given in the algorithm
below. The first 3 steps in the algorithm below are for the function foo().

Algorithm:

a. Store the number as a string in variable s.


Prepared By: Rehan Naeem
Formatted By Khushbakht
Department of Electrical Engineering
28

b. While iterating over variable s


If the character in s is 1, increase variable a by 1.
Else if the character in s is 2, increase variable b by 1.
Else if the character in s is 3, increase variable c by 1.
c. Return a, b, and c.
d. Display the four lines as shown in the output below.

Test Case 1: The following output comes when


a=”1233”

Test Case 2: The following output Test Case 3: The following output
comes when a=”11112333” comes when a=”12213233”

9. Decoding a Secret Message: You can hide a secret message in a piece of text by setting a specific
character as a key. Place the key before every letter in the message, then fill in extra (non-key)
letters between key-letter pairs to hide the message in noise. For example, to hide the message
"computer" with the key "q", you would start with "computer", turn it into "qcqoqmqpquqtqeqr",
and then add extra letters as noise, perhaps resulting in
"orupqcrzypqomqmhcyqpwhhqutqtxtqeyeqrpa". To get the original message back out, copy
every letter that occurs directly after the key, ignoring the rest.

Write a function getSecretMessage(s, key) that takes a piece of text holding a secret message and the key
to that message and returns the secret message itself. For example, if we called the function on the long
string above and "q", it would return "computer".

Test Case 1: The following output comes when


getSecretMessage(“qcqoqmqpquqtqeqr”,”q”) is called.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
29

Test Case 2: The following output comes when


getSecretMessage(“orupacrzypaomamhcyapwhhautatxtaeyearp”, ”a”)
is called.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
30

Lab 5: Implementation of Nested Loops and


Function Scope in Python

Things to be covered in this experiment.


• Concatenation
• Functions
• Printing Pyramids
Recommended To DOs: You can watch my lecture here related to experiment 5. This video might not
cover all the concepts required for completing the experiment. So, coming to the lab is a must.

1. Determine the output of the following code without using the computer.

Code 1 Code 2

Code 3 Code 4

2. Completing Code: Complete the following program to get the output as shown below. Hint: The
print statement at line 64 runs once to print one 1, twice to print two 2s, thrice to print
three 3s and so on.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
31

Code Output

3. Writing code from Flowchart: Convert the following flowchart to python code to get the output
as shown below.

Flow Chart Output

4. Determining factors using functions: Using the algorithm shown below, write the function
PrimeFactors(x) which takes a positive integer x and prints all its prime factors in a nice
format. A prime factor is a number that is both prime and it evenly divides the original number (with
Prepared By: Rehan Naeem
Formatted By Khushbakht
Department of Electrical Engineering
32

no remainder). So, the prime factors of 70 are 2, 5, and 7, because 2 * 5 * 7 = 70. Note that 10 is
not a prime factor because it is not prime, and 3 is not a prime factor because it is not a factor
of 70. Prime factors can be repeated when the same factor divides the original number multiple
times; for example, the prime factors of 12 are 2, 2, and 3, because 2 and 3 are both prime and 2 * 2
* 3 = 12. The prime factors of 16 are 2, 2, 2, and 2, because 2 * 2 * 2 * 2 = 16. We'll display repeated
factors on a single line as a power expression; for example, 16 would display 2 ** 4, because 2 is
repeated four times. Here's a high-level algorithm to solve this problem. Start by iterating through
all possible factors. When you find a viable factor, repeatedly divide the number by that factor until
it no longer evenly divides the number. Our algorithm (pseudocode) looks something like this:
1. Repeat the following procedure over all possible factors (2 to x)
a. If x is evenly divisible by the possible factor.
i. Set the number count to be 0.
ii. Repeat the following procedure until x is not divisible by the possible factor.
1. Set count to be count plus 1
2. Set x to x divided by the factor
iii. If the number count is exactly 1.
1. Print the factor by itself
iv. If the number count is greater than 1.
1. Print "f ** c", where f is the factor and c is the count.

Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
33

5. Prime Numbers: Write a program which prints all the prime integers up to 50. Hint: A prime
number is a number which is completely divisible by 1 or by itself and not by rest of the integers.
Integers 0 and 1 are not prime. Also count and display the number of prime numbers from 0 to 50.
6. Printing Pyramids: Write a program that prompts the user to enter the number of rows of a
pyramid and it then displays the pyramid at the output according to the number of rows given by
the user. Use nested for-loops to get the output.

Output 1 Output 2

7. Printing Diamonds: Write a program that prompts the user to enter the number of rows of a
diamond and it then displays the diamond at the output according to the number of rows given by
the user. Use nested for-loops to get the output.

Output 1 Output 2

8. Function as a function’s arguments: Write a function foo(n, f, g) which takes 3 arguments where n is
a number, f and g are two functions. The function foo(n, f, g) should return True if f(g(n)) is equal to
g(f(n)). Write another function add one(n) which adds 1 to n and returns the sum. Write another
function square(n) which squares n and returns it. The functions foo(n, f, g), add one(n) and
square(n) should not be nested rather written separately. For example, print(foo(4, add one, square))
should calculate (4)2 + 1 and (4+1)2 and return False since (4)2 + 1 ≠ (4+1)2 . Similarly print(foo(0, add
one, square)) should return True. In the future lab, you will see that using a higher order function
increases the abstraction layer of this code. Increasing abstraction level helps to create programs without
worrying too much about the underlying implementation details.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
34

Lab 6: Implementation of Higher Order


Functions in Python
Things to be covered in this experiment.
• Higher Order Functions
• Functions as arguments
• Composite Functions
Recommended To DOs: You can watch my lecture here related to experiment 6. This video might not
cover all the concepts required for completing the experiment. So, coming to the lab is a must.

1. Higher Order and Lambda Functions: Determine the output of the following codes without using
the computer. Draw environment diagram for each code.

Code 1 Code 2

Code 3 Code 4

Code 5
Prepared By: Rehan Naeem
Formatted By Khushbakht
Department of Electrical Engineering
35

2. Error message upon execution: Explain why the following code outputs an error message when
executed. Draw environment diagram to answer in a better way.

Code

3. Flow that Yo-Yo: The following environment diagram was generated by a program:

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
36

Environment Diagram

In this series of questions, you’ll fill in the blanks of the program that follows (see table below) so that
its execution matches the environment diagram. You may want to fill in the blanks in a different order;
feel free to answer the questions in whatever order works for you.

Code Question 1 and 2

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
37

Question 3 and 4 Question 5 and 6

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
38

4. Function calling a Function, Function as A Function’s Argument: Consider the following two
functions, which all compute summations. The first, sum_naturals, computes the sum of natural
numbers up to n:
>>> def sum_naturals(n):
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total

>>> sum_naturals(100)
5050

The second, sum_cubes, computes the sum of the cubes of natural numbers up to n.
>>> def sum_cubes(n):
total, k = 0, 1
while k <= n:
total, k = total + k*k*k, k + 1
return total

>>>sum_cubes(100)
25502500

These two functions clearly share a common underlying pattern. They are for the most part identical,
differing only in name and the function of k used to compute the term to be added. We could generate
each of the functions by filling in slots in the same template shown below

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
39

The presence of such a common pattern is strong evidence that there is a useful abstraction waiting to be
brought to the surface. Each of these functions is a summation of terms. As program designers, we would
like our language to be powerful enough so that we can write a function that expresses the concept of
summation itself rather than only functions that compute particular sums. We can do so readily in Python
by taking the common template shown above and transforming the "slots" into formal parameters.

Complete the above program which should print


• Summation of cubed integers up to n when summation(n, cube) is called, where n is any
integer and cube is a user-defined function. For example, summation(3,cube) should return
𝟏𝟑 + 𝟐𝟑 + 𝟑𝟑 which is 36
• Summation of natural integers up to n when summation(n, naturals) is called, where n is any
integer and naturals is a user-defined function. For example, summation(3, naturals) should
return 𝟏 + 𝟐 + 𝟑 which is 6

5. Higher Order Function returning a Function: Write a function mutliply_by(m) which takes
in a number m and returns a function multiply(n) that can take in a single integer n as a
parameter. This returned function multiply(n) should return the product of m and n when
called. For example, times_three(5) should print the product of 3 and 5. Alternatively,
multiply_by could be called directly to print the product of 3 and 10 as shown below.

Code Output

6. Higher Order Function: Write a function make_keeper(n) that takes in a number n and
returns a function f( ). Function f( ) takes in a single parameter cond which is a user-defined
function. When we pass in cond into this function f, the function f( ) prints out numbers from 1
to n if calling cond on that number returns True. For example, when
make_keeper(6)(is_even) is called, the function f( ) iterates over all the integers from 1 to 6
and prints the even numbers only.

Code Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
40

7. Composite Functions: Write a function compose(f, g) which takes two user-defined functions f and g
as arguments and returns a user-defined function foo( ). The function foo( ) takes a number x as an
argument and returns f(g(x)). Also write a lambda function square() to square a number and a lambda
function triple() to triple a number. Will you define the functions foo, square and triple inside
compose function or outside and why? Note: The function compose( ) does the job of square(triple(2))
and triple(square(2)) or more generally f(g(x)).

Code

Challenge: Can you write only a single return statement inside the compose function so that it
performs its required job!!
8. Composite Functions: Write a function composite_identity that takes in two single-argument
functions, f and g, and returns another function h that has a single parameter x. The function h() should
return True if f(g(x)) is equal to g(f(x)). You can assume the output of g(x) is a valid input for f and vice
versa. To find f( g(x) ) or g( f( x ) ) use the function compose written in question 5. This task performs
calculations and outputs results like task 7, lab 6. The only difference is that this code is more abstract
than the previous one (More on abstraction in the lab lecture).

Code

9. Digit Replacer: The function digit_replacer (predicate, transformer) should return a function that
accepts a single number n (where n > 0) and returns a number where all digits that return true for
predicate(digit) have been replaced by transformer(digit). The function transformer is assumed to
always return a valid digit >= 0 and <= 9. Note: predicate and transformer are two user-defined functions
(See the code below).

Code Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
41

Lab 7: Implementation of 1D and 2D Lists in


Python
Things to be covered in this experiment.
● Introduction to 1D lists
● Introduction to 2D lists
● Functions using lists
Recommended To DOs: You can watch my lecture here related to experiment 7. This video
might not cover all the concepts required for completing the experiment. So, coming to the lab is a
must. Note: If you are unsure anything related to PYTHON, then use this website
https://docs.python.org/3/

1. Tracing the code: Trace the following codes without using the computer. Draw the environment
diagram for code 1
Code 1 Code 2 Code 3

Code 4

Code 5

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
42

2. 1D List: Write a program which calculates the sum and average of all the prices of a product stored
in a list called price. Don't use any user-defined / built-in function. The program should also print the
individual price and the index no. at which the price is present. The program should work correctly
for any length of the list price. For example, the output should be as shown below for price = [40,
5.3, 7.8, 1]:

Output

3. 2D List: A. Create a 2D list called CitiesList having 3 sub-lists. Each sub-list should contain a city name
and a province name according to the table shown below.
B. Write a function getProvince(CitiesList, cityName) which takes two arguments; a 2D list called
CitiesList and a city name in the form of a string. The function should return the name of the
province of the city stored in cityName otherwise None should be returned. For example,
print(getProvince(CitiesList, ‘Lahore’)) should print ‘Punjab’ whereas
print(getProvince(CitiesList, ‘uet’)) should print None.

City Names Province Names

Lahore Punjab

Gilgit GB

Karachi Sindh

4. Function Arguments as 1D Lists and 2D List Return Value + List Comprehension: Implement the
function couple, which takes in two lists and returns a 2D list in which each sub-list contains the i-
th elements of two sequences coupled together. You can assume the lengths of two sequences to be
the same. The code should work for any length of list a and b.
Code Output

Challenge: Use a single line (list-comprehension) code inside the function couple to return the
required list.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
43

5. Non-Destructive Function with 1D list argument and 1D list Return Value: Write a non-
destructive function findMultiples(L, num) that takes a list L of integers and a positive integer num,
and returns a new list containing only the elements that are multiples of num in L. For example,
FindMultiples( [11, 20, 35, 43, 50], 5) returns [20, 35, 50] when called. Your code should print the
returned list. Note: Non-destructive function does not modify the original list L.

6. A. Destructive Function: Write a destructive function foo(L) that takes a list L of integers, and
destructively doubles the positive elements of L i.e., the positive integers of the original list a (shown
below) should be doubled This function should return None instead of the list. The code should work
correctly for any size of list a. Note: Don't make a new list to store the required list. Destructive
function is the one which modifies the original list L.
Code Output

B. Repeat part A for the 2D list shown below. The code should work correctly for any size of list a
and any size of its sub-lists. This function should return None instead of a list. Note: Don't make
a new list to store the required list.
Code Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
44

7. Returning list from script: You're provided a string script here. Copy the script and store it in a
variable called script. Each line of the script begins with a character's name, followed by a colon,
followed by their line of dialogue. Lines are separated by newlines, which are represented in Python
by the string '\n'.

Code

Using the algorithm provided below, write the function getCharacterLines(script, character), which
takes a script and a character name (both strings) and returns a list of the lines spoken by that
character. The lines should be stripped of the leading character name and any leading/trailing whitespace.
So, if we use the following script:
Should print
Output

To do this:
1. You should first split the script into lines
2. Then, iterate over the lines of the script
a. For each line, you should check if the character who is saying that line is the character
that was given to you as a parameter.
b. If it is, separate the dialogue line from the rest of the string (note that it occurs after the
colon) and strip any leading/trailing whitespace from it
c. Add the resulting line to a list where you are keeping track of all the lines for this
character.
3. You should return the list of all the lines for this character.
Hints: use .split() to separate lines of the text and .strip() to remove excess whitespace from the front and
end of the string

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
45

8. Modifying the code: Code 2 and 3 in question 2, fail to remove 3 successfully from list a. Write a code
using a while-loop to remove 3 successfully.

9. Optimizing the code for Fast Cache Access: Write a program which creates a n x n matrix of
integers and calculates the sum of all the integers using the following algorithms. The sum should
then be printed in the output window. Assume all the integers to be equal. You can think the matrix to
be a 2D list in which a sub-list is the row. The program should work for any value of n.
Algorithm 1:
a. Calculate the sum of all the integers in the 1st row by accumulating the sum of two consecutive
integers in the row.
b. Then go to the 2nd row and repeat the above step. Keep on repeating the same procedure till
all the n rows are covered.
Algorithm 2:
a. Calculate the sum of all the integers in the 1 st column by accumulating the sum of two
consecutive integers in the column.
b. Then go to the 2nd column and repeat the above step. Keep on repeating the same procedure
till all the n columns are covered.

One of the two algorithms runs faster than the other. Can you tell which one and why? Discuss with
your instructor. This task makes us realize the importance of optimizing the code to improve
performance i.e., execution time. This task also highlights the importance of knowing about the
architecture of the computer (More on this in the senior years) in order to get maximum
performance from the code. Later in future lab you will use PYTHON to find the execution time of
both the algorithms given above.
Note: A cache is a small size, fast memory used for fast data access.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
46

Lab 8: Implementation of Recursion in Python


Things to be covered in this experiment.
● Introduction to Recursion
● Recursion using functions
Recommended To DOs: You can watch my lecture here related to experiment 8. This video
might not cover all the concepts required for completing the experiment. So, coming to the lab is a
must. Note: If you are unsure anything related to PYTHON, then use this website
https://docs.python.org/3/

1. Output without computer: Determine the output of the following codes without using the
computer. How many times does the function luhn_sum(n) call the function luhn_sum_double(n)
and vice versa in code 2?

Code 1 Code 2: Mutual Recursion - The LUHN Algorithm

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
47

2. Errors: Assume line 7, 9 and 10 in the following code to be corrected, point out and correct the
errors in the code. After correction, determine the output of the code.
Code

3. Writing a recursive function: Write a recursive function mul(m, n) that returns the product of
two numbers m and n. From the ucb module, import trace and use @trace to print the recursive
function calls and their returned values. Download the ucb.py file here and paste it in the folder
where the code for this question is saved.
Challenge: print the depth of the recursive calls i.e., the no. of times function mul(m,n) is called.

4. A. Recursive function which returns sum of numbers: Write a recursive function add(L) that
takes a list L of numbers and returns the sum of all the numbers in the list. Print the returned list.
B. Tree Recursion: Solve the problem in part A using Tree Recursion i.e., divide the list into two
halves.

5. Recursive function which returns vowels: Write a recursive function NoOfVowels(s) which
counts and returns the number of vowels in the string s.

6. Complete the code: Complete the recursive function RemoveDuplicates(L) which takes a list L of
numbers and returns a new list that contains only one of each unique item from the original list
in any order. For example, RemoveDuplicates([1, 2, 1, 2, 3, 4, 3, 3]) might return [1, 2, 3, 4]. Print
the returned list.

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
48

7. Recursive function which returns indices: Write a recursive function RecursiveMatch(L1, L2),
which takes two lists of equal length and returns the number of indices where L1 has the same value
as L2. For example, RecursiveMatch( [4, 2, 1, 6], [4, 3, 7, 6] ) should return 2 since the element 4
and 6 in list L1 and L2 match each other. Print the number of indices.

8. Recursive function which returns longest string: Write a function recursiveLongestString(L)


that takes a list L of strings as input and returns the longest string in the list. You may assume the
list contains at least one element and there will not be a tie. For example,
recursiveLongestString(["a", "bb", "ccc"]) returns "ccc", and recursiveLongestString(["hi",
"its", "fantastic", "here"]) returns "fantastic". Print the longest string.

9. Recursive Hailstone: The function hailstone(n) picks a positive integer n as the start. If n is even,
divide it by 2. If n is odd, multiply it by 3 and then add 1. Repeat this process until n is 1. Write a
recursive version of hailstone that prints out the values of the sequence and returns the number of
steps.

10. Recursive Merge: Write a function merge(L1, L2) that takes 2 sorted lists S1 and S2 and returns a
new list that contains all the elements in the two lists in sorted order as shown below.

Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
49

Lab 9: Dictionaries and Exception Handling in


Python
Things to be covered in this experiment.
● Introduction to Dictionaries
● Exceptions
Recommended To DOs: You can watch my lecture here related to experiment 8. This video might
not cover all the concepts required for completing the experiment. So, coming to the lab is a must.
Note: If you are unsure anything related to PYTHON, then use this website
https://docs.python.org/3/

1. Determining the output: Determine the output of the following program without using the computer.
What does code 3 do?
Code 1 Code 2

Code 3

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
50

2. Creating Dictionary: Create a dictionary from the table given below. Then prompt the user to enter the
name of any city. If the city is in the dictionary, then print the city and its province, otherwise print the
city is not in the dictionary.

Keys Values
Output
Lahore Punjab

Peshawar KPK

Karachi Sindh

Quetta Balochistan

Gilgit GB

3. Mapping using Dictionary: Write a function foo(s) which takes in a string s, maps the frequency of how
many times a character appears and returns a dictionary that has the mapping. For example, for the string
‘banana’ the output should be

Output

4. Dictionary which returns required output :Write a function foo(bookInfo, author) which takes in a
dictionary bookInfo and a string author. The dictionary bookInfo has book titles (strings) as keys and
author names (strings) as values. The function foo should return the book title corresponding to the author.
For example:
Code

Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
51

5. Dictionary which returns key-value pair: The fruits in a bag of groceries are provided as a list (e.g.
["apple", "oranges", "banana", "kiwis"]). For any elements in the list that are plural, like “kiwis”, we
say there are 3 of that fruit in the bag. Write a function groceryCount that outputs a dictionary with each
fruit name and its frequency as a key-value pair. For example:

Code

Output

6. Memoization: The code below calculates and prints the time needed to execute the function fact()
which calculates the factorial of integers 1 to 250. Run this code and write down the time required.

a. Note that fact(n) = n * fact(n-1). Inside the function fact(n), use a dictionary to store fact(n-1)
so that when fact(n) is called, it gets the value of fact(n-1) from the dictionary instead of
calculating it which is time consuming. Don’t modify anything else outside the function fact(n).
Write down the time required by the modified code to calculate the factorials. You will observe
this time to be lesser than the one found in part a. Memoization is very similar to how real
processors use multi-level Caches to reduce data access latency. More on this in the Computer
Architecture course and more on time.time() in the last experiment.

Code

7. Catching Exception in a code: In this question related to the calculation of roots, Zero Division
Error exception is raised when coefficient a = 0. Write additional code to that you have already
written, to catch the exception. When an exception is caught display the message "Coefficient 'a'
can't be zero!". Don’t prompt the user for the input.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
52

8. Catching Exception in a Function: Consider the above question, now use a function to calculate
the roots as done in this question. Write a code to catch the exception raised when a = 0 and the
exception when a is not a number. Don’t prompt the user for the input. For the first exception display
the message "Coefficient 'a' can't be zero!" and for the second exception display the message
"Coefficient 'a', 'b' and 'c' should be a number!"

9. Catching Exception in A Loop: Write a program that sums only the integers. Prompt the user to
enter the integer till 0 is entered. If anything, other than a number is entered then catch the
exception and display the message “Didn't enter a Number. Try again!”. Note: The built-in function
int raises an exception when its argument is not a number. Can you tell the type of exception raised by
the built-in function int?

Output

10. In code 3, question 1, two types of exceptions are raised when the list of marks is empty or when
the list contains an element which is not a number.
a. Write the names of the exceptions raised when the code encounters the situations mentioned
above.
b. Add code to handle the exceptions mentioned in step a. The code should not compute
anything further when any exception occurs. For example if d1 = { 'ali':[1,'a'] , 'amna':[1, 2] }
then the code should not compute Amna’s average marks and terminate after printing
dictionary d2. The code should also print a suitable message reflecting the student’s name
whose list caused the exception and the type of exception.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
53

If d1 = { 'ali':[1,'a'] , 'amna':[1, ‘d’] } then the output should be

Can you use the keyword except only to handle the exceptions in this part? Give reason?

c. Add code to handle the exceptions mentioned in step a. The code should continue to compute
average even if an exception occurs. For example if d1 = { 'ali':[1,'a'] , 'amna':[1, 2] } then the
code should compute Amna’s average marks and terminate after printing dictionary d2. The
code should also print a suitable message showing the student’s name whose list caused the
exception.

d. Challenge: Add some code to the one you wrote in part c to print the index of the element
causing the exception as mentioned in part a. For example if d1 = { 'ali':[1,'a'] , 'amna':[1, 2] }
then the output should be

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
54

Lab 10: Implementation of Object-Oriented


Programming in Python

Things to be covered in this experiment.


● Introduction to Object Oriented Programming
● Exceptions
Recommended To DOs: You can watch my lecture here related to experiment 10. This video might
not cover all the concepts required for completing the experiment. So, coming to the lab is a must.
Note: If you are unsure anything related to PYTHON, then use this website
https://docs.python.org/3/

1.Determining Output: Determine the output of the following codes without using the computer.
Code 1 – Part 1 Code 1 – Part 2

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
55

A) In code 2, which of the following expressions evaluates an integer?


● b.z
● b.z.z
● b.z.z.z
B) In code 4, class D inherits from its two parent classes B and C hence the name multiple inheritance.
The C3 Method Resolution Ordering recursive code is used to resolve attribute lookup issues in case
of multiple inheritance. Write this line print( [c.__name__ for c in D.mro()] ) at the end of code 4a
and find out the lookup order.

Code 2 Code 3

Code 4: Multiple Inheritance


4a 4b 4c 4d

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
56

2. Completing code: Complete the following code by writing a class Bird having
a. Two instance attributes to store the name of the bird and to store initial value of egg count.
b. A method fly which returns the string “I can fly!”
c. A method layEgg which increments the egg count by 1.
d. A method countEggs which returns the number of eggs laid by the bird.
The code outside the class can be downloaded here. If you don’t get any error while executing the
code, it means you’ve written the class correctly. Recall the function of assert!

Code

Challenge 1: Consider the variable storing the egg count to be the class attribute. Modify the class
Bird accordingly to get the correct output.
Point to Ponder: Can the variable storing the egg count be a local variable of any of the class
methods? Justify.
Challenge 2: Write a method BirdCount which returns the number of instances of class Bird
created.
3. Completing code: Complete the following code by writing the class MarksCounter. Look at the code
from line number 95 to 98 and at the output to write the class correctly.

Code Output

a. A few more lines of code have been added to the above code (line 116 to 118). Modify the class
to get the output as shown below

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
57

Code Output

4. Completing code: Complete the following code by writing the class Person. Look at the code from
line number 143 to 155 and at the output to write the class correctly. The code outside the class can
be downloaded here. If you don’t get any error while executing the code, it means you’ve written
the class correctly.
Code

5. The class Pet has been implemented for you. Study it carefully and then solve the following parts.
You can download and use the implemented and incomplete codes for all the parts here.

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
58

a. Below is a skeleton for the Cat class, which inherits from the Pet class. To complete the
implementation, override the __init__ and talk methods and add a new lose_life method.
Read the docstrings carefully to get the correct output.

Code

b. More cats! Fill in this implementation of a class called NoisyCat, which is just like a
normal Cat. However, NoisyCat talks a lot: in fact, it talks twice as much as a regular Cat!

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
59

6. Write a class ComplexRI which has two instance attributes i.e. ‘real’ to store the real and
‘imaginary’ to store the imaginary part of a complex number. Study the rest of the code and the
output carefully to write the rest of attributes and methods.

Code Output

7. Write a class ComplexMA which has two instance attributes i.e. the magnitude and the angle (in
degrees) of a complex number. Study the rest of the code and the output carefully to write the rest
of attributes and methods.

Code Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
60

Lab 11: Object-Oriented Programming in Python


– Part 2

Things to be covered in this experiment.


● Introduction to Object Oriented Programming
● Exceptions
Recommended To DOs: You can watch my lecture here related to experiment 11. This video
might not cover all the concepts required for completing the experiment. So, coming to the lab is a
must. Note: If you are unsure anything related to PYTHON, then use this website
https://docs.python.org/3/

1. Determine the output of the following code without using the computer.
Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
61

2. Write a class Vehicle to get the output as shown below. By looking at the code, determine the
instances, attributes, methods, parent and/or child class(es). Note: Three vehicles are created i.e.
v1, v2 and …. Where is the 3rd vehicle created?

Incomplete Code Required Output

3. Inheritance: Write a child class Car of the parent class Vehicle to get the output as shown below.
Note: The move() and the brake() methods are inherited from the Vehicle class. By looking at the
code, determine the instances, attributes, methods, parent and/or child class(es).

Incomplete Code Required Output

4. Write a class Ratio to get the output as shown below. By looking at the code, determine the
instances, attributes, methods, parent and/or child class(es).

Incomplete Code Required Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
62

5. The code below adds complex numbers. One complex number is in rectangular while the other is in
polar form. Modify the ComplexRI and ComplexMA classes you wrote in lab 10 to get the output
shown below. Note: Don’t use __radd__ method.

Code Code

Challenge: Write a class Foo having one add method defined to add c1 and c2 in any order. This class
should be the parent of ComplexRI and ComplexMA classes. The class Foo is the interface class. This
challenge is possible if you have done part a of this question correctly.
6. Complete the following code so that no “Assertion Error” message is displayed when the code runs.

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
63

7. Looking at the codes below, write a object-oriented program which when executed does not give the
“Assertion Error” message. By looking at the code, determine the instances, attributes, methods, parent
and/or child class(es) unless mentioned explicitly. In code 1, Chapter and Book are separate classes.
Write the two codes in separate files.

Code 1 Code 2

8. A mint is a place where coins are made. In this question, you'll implement a Mint class that can
output a Coin with the correct year and worth.
● Each Mint instance has a year stamp. The update method sets the year stamp of the instance
to the present_year class attribute of the Mint class.
● The create method takes a subclass of Coin (not an instance!), then creates and returns an
instance of that class stamped with the mint's year (which may be different from
Mint.present_year if it has not been updated.)
● A Coin's worth method returns the cents value of the coin plus one extra cent for each year
of age beyond 50. A coin's age can be determined by subtracting the coin's year from the
present_year class attribute of the Mint class.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
64

Code

B. Assume that you have written the above code completely and correctly, determine the output of the
above code if the following lines are added below line 41 of the above code.

Code

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
65

Lab 12: Plotting Data + Iterators & Generators in


Python

Things to be covered in this experiment.


● Use MATPLOTLIB and NUMPY tools to create and plot the data.
● Iterators and Generators in Python.
Recommended To DOs: You can watch my lecture here related to experiment 12. This video
might not cover all the concepts required for completing the experiment. So, coming to the lab is a
must. Note: If you are unsure anything related to PYTHON, then use this website
https://docs.python.org/3/

1. Iterator and Generator: Determine the output of the following code without using the computer

Code 1 Code 2

2. Generator: Implement the generator function three_flips(). It takes as input a (potentially infinite) iterator
coin, each element of which is either 'H' or 'T' (denoting coin flips of Heads and Tails, respectively). It yields
a sequence of triples of coin flip outcomes from coin.

Code Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
66

3. Iterator: Implement count_occurrences, which takes an iterator t and a value x. It returns the
number of elements equal to x that appear in the first n elements of t.
Code Output

4. Write a generator function foo(a, b) which takes two lists a and b and yields their values.

Code Output

5. Write a program to get the output as shown below.

Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
67

6. Write a program to display a sinusoidal wave as shown below. For this purpose, define a function Sine()
that takes the amplitude, frequency, phase shift in degrees, stop time, label, and color of the plot as inputs.
Define another function SetPlot() to label the plot, give title to it, display the grid and the legends.
Complete the code shown below to get the required output. The general equation of a sinusoidal wave is
y = A * sin( (2*𝝅*f*t) + 𝝋)
where A = amplitude of the sine wave, f = frequency of the sine wave in Hertz (Cycles/Sec), 𝜑 = Phase shift of the sine wave t = time in
seconds

Incomplete Code Output

7. Write a program to display three sinusoidal waves in one figure as shown below. For this purpose, use
the function Sine() you wrote in question 2 to plot one sine wave. Complete the code below to get the
output shown below. The general equation of the three sinusoidal waves are:
v1 = A * sin( 2*pi*f*t )
v2 = A * sin( (2*pi*f*t) + 120°)
v3 = A * sin( (2*pi*f*t) + 240°)
Where A = Amplitude of the sine wave, f = Frequency of the sine wave in Hertz (Cycles/Sec) , t = time in seconds

Output

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
68

8. Write a program to display two circles with their centers as shown below. In the figure below, both
circles have radius = 4 and centers at (2,15) and (15,15). The equation of a circle is
(𝒙 − 𝒂)𝟐 + (𝒚 − 𝒃)𝟐 = 𝒓𝟐
where ‘a’ and ‘b’ are the coordinates representing the center of the circle and ‘r’ is the radius of the circle.
The inputs are a, b, r, color of the circle and name of the circle. It is better to define a function PrintCircle()
that takes these inputs as parameters and prints the circle with the center.

Output

9. Matrix Operations:
a. The diagram below shows an electrical circuit having eight resistors. To calculate potentials
vB, vC, vD and vE, four equations are needed to be solved simultaneously. The coefficients
and constant values in the four equations can be stored in matrices A, X and B shown below.
Use NumPy to find voltages vB, vC, vD and vE where 𝑿 = 𝑨−𝟏 𝑩. Assume R = 1ohms and vS
= 1V
b. Find the voltage across each resistor by calculating the difference in potentials at both of its
sides. For example, voltage across R1 is vB – vA.
If the circuit becomes large, i.e., having many loops (more on this in the Electric Circuits course)
then the number of equations needed to be solved simultaneously also becomes large and you can
no longer solve them manually. This is where programming comes in as a useful skill to take
advantage of!

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
69

10. Vectorization:
a. Write a program which multiplies two sequences of integers A and B and sums all the
products to get S as shown below. Sequence A and B contain 50000 integers. Store sequence
A and B in two lists.

𝑨 = 𝟎, 𝟏, 𝟐, . … … … … , 𝟒𝟗𝟗𝟗𝟗
𝑩 = 𝟑, 𝟑, 𝟑, . … … … … , 𝟑
𝑺 = (𝟎 × 𝟑) + ( 𝟏 × 𝟑) + (𝟐 × 𝟑) + ⋯ . +(𝟒𝟗𝟗𝟗𝟗 × 𝟑)
b. The sum S could also be computed if sequence A and B are stored in the form of matrices or
vectors. You can use dot product concept or matrix multiplication to compute S.
c. Find the execution time of the codes in part a and b. Discuss this with your instructor.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
70

Lab 13: File Handling & Working with Tabular


Data in Python
1 In this task, you will be working with the folder named “New Folder”. Download it here and place it
on the desktop.

Write a code to create three directories named pdfs, word and notepad in New Folder.
The New Folder directory contains folders, image files, word file and pdf files. Write a code
1. to copy and paste all pdf files into the pdfs folder.
2. To move word and text files into the word and notepad folder respectively.
3. To copy and paste folder named x into the pdfs folder.
4. To move folder named y into the word folder.
5. To delete the sub folder named videos.
Write one code only to perform the above tasks.

2. Write a code to delete all the image files present in the New Folder. Assume that the images could be,
at max, present in the sub folders of the New Folder and not deeper.

3. The text file named putty has the values measured by accelerometer and gyroscope in real time as
shown below. These values were measured and sent to the computer / laptop using a microcontroller
named TIVA (more on this in the 3rd year). The text file has numerous values of acceleration along
x, y and z axes and orientation along x, y and z axes, hence difficult to understand ther trend. Write
a code to read the text file putty.log and plot the values of Ax, Ay, Az, Gx, Gy and Gz where Ax is
the acceleration along x axis and Gx is the orientation along x axis.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
71

4. BoxPlot and Pandas: The excel file Result Sheet - EEE S23.xlsx (it is present in the folder New
Folder mentioned above) contains marks of students belonging to section A, B, C and D. Open the
file and explore it. There is a column named Grand Total having total marks scored by each student
in a particular course. Your task is to create boxplots with Grand Total on the y-axis, for each section
as shown below. Use PANDAS to import the excel sheet data, preprocess it to remove missing
values and slice the dataframe to plot the boxplot for each section. The boxplot method will not work
if missing values are not removed.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
72

5. Adfdfsfd

6. Vcvc

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
73

First update the PANDAS library by typing the following command in spyder console:

Professor Melon Usk is required to submit a report having some data related to the course he teaches at a
university. He maintains a students marks sheet on which the report is based. On the basis of that report,
the toppers of the course will be awarded and the failures will be asked to repeat the course. Professor
Melon is a very busy professor and has no time to create the report. So he hires you to get the job done.
Your job is to write a code to generate that report.
a. Create a dataframe and store the table given in this markssheet. Print the dataframe as
shown below.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
74

b. Modify the dataframe to get the one shown below.

c. Professor Melon is interested in seeing the mean, minimum, and maximum marks scored in
each of the quiz and the exam. Write one line of code to help him out. Note down the values
in your copy.
d. Professor Melon now wants to categorize the students into best, average and below average
students. This can be done by sorting the students on the basis of their total marks. Write one
line of code to sort.
e. Professor Melon awards grades as follows.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
75

● Grade B- is awarded to those students whose marks lie in the range R = [ (A (− 0.5
* SD) ). . . . . (A + (0.5 * SD) ) ] where A and SD are the average and standard deviation
of the total marks of the whole class.
● Grade A is awarded to those whose percentage marks are above the range R and
greater than 85 percent.
● Grade B is awarded to those whose percentage marks are above the range R and
less than equal to 85 percent.
● Grade C is awarded to those whose percentage marks are below the range R and
greater than 33 percent.
● Grade F is awarded to those whose percentage marks are below the range R and less
than equal to 33 percent.
Your code should determine the correct grade for each student and display it in a new
column ‘grades’ in the dataframe.
f. Now write a code to create a report as shown below. The report in excel format, contains the
total number of students in the class, the roll numbers who topped the course, the students
who failed and a plot which is self-explanatory. Hint: Use xlsxwriter library to create and
modify excel files.

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
76

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
77

Lab 14: Signal Manipulation & Processing in


Python

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
78

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
79

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
80

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
81

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
82

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
83

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
84

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
85

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering
86

Prepared By: Rehan Naeem


Formatted By Khushbakht
Department of Electrical Engineering

You might also like