0% found this document useful (0 votes)
70 views64 pages

ITC Lab Manual - Fall 2022

The document describes an experiment on implementing non-nested loops in Python. It includes questions on writing functions to print strings multiple times using for loops, taking name and number of times as arguments. Draw flowcharts before coding questions involving conditional statements. Determine outputs without running code for some questions.

Uploaded by

raqeemuetian86
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
70 views64 pages

ITC Lab Manual - Fall 2022

The document describes an experiment on implementing non-nested loops in Python. It includes questions on writing functions to print strings multiple times using for loops, taking name and number of times as arguments. Draw flowcharts before coding questions involving conditional statements. Determine outputs without running code for some questions.

Uploaded by

raqeemuetian86
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 64

Lab # 1

Implementation of PRINT statement in


PYTHON
Things to be covered in this experiment
● Introduction to SPYDER software
● PRINT statement
● Use of \n and end=””
1. Eliminate all the syntax errors in the following code to get the output in the console
window as shown below
Code

Output

2. Write a program that prints the message as shown below. Use multiple print statements to
get the output.
Output

3. 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.
Pay attention to the number of rows, the number of asterisks (*) and the number of
spaces before * in each row.
Output
2
4. Write a program that calculates the roots of a quadratic equation 3𝑥 + 𝑥 − 2. Store the
coefficients of the quadratic equation in variables a, b and c. Then calculate the roots and
display them at the output. The formula to calculate the roots is
2
−𝑏 ± 𝑏 −4𝑎𝑐
𝑥= 2𝑎
Output

5. A right angle triangle having A = 50 metres and C = 10 metres 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.

−1
α = 𝑐𝑜𝑠 (𝐶/𝐴)

𝐵 = 𝐶 × 𝑡𝑎𝑛 (α)

Output

6. 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.
Output

7. Determine the output of the following program without using the computer.
Experiment # 2
Implementation of Comparison and Logical
operators in Python
Topics to be covered in this Lab Manual
● Conditional Statements
● Comparison and Logical Operators
Note: Use a single expression containing comparison and/or logical operators inside a single
print instruction to solve question 1 to 6. Dont use IF-ELSE or any other conditional
statement. You are not required to take input from the user in question 2 to 6.
1. Prompt the user to enter marks (only integers) of two subjects i.e. Maths and Urdu. The
program should print True if marks in both the subjects are greater than 5 otherwise
False should be printed at the output.

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

3. Suleman will only wear a jacket outside if the temperature is below 60 degrees or it is
raining. Write a program that prints True when Suleman wears the jacket otherwise prints
False. Use boolean value True to indicate to the computer that it is raining. Complete the
following program to get the output as shown below. You can only fill line 15, 16 and 17.
Don't add or delete anything else in the code.
4. Write a program which stores a number into a variable. The number could be an integer
or a floating point number. The program should print True if the number is an integer
otherwise print False at the output.

5. Write a program which calculates the sum of three numbers 0.1, 0.1, and 0.1 and
compares this sum with 0.3. What problem did you notice in this question?

6. Abdullah is happy when he gets a whatsapp message from either Ali or Umar and not
from Salman. Write a program that prints True when Abdullah is happy and False
otherwise. Use boolean value True to indicate Ali, Umar, Salman sending the message
and False otherwise.

7. Draw, on a piece of paper, the Environment Diagram for the following code. Also
determine the output. Note: min and max are built-in functions to find minimum and
maximum value in a set of numbers.

8. Determine the output of the following without using the computer. Also give reason(s).
Part a Part b Part c
Experiment # 3
Implementation of Conditional Statements in
Python
Note: Draw a flowchart before coding question number 3 to 6. Don't prompt
the user for any input in question 3 to 6.
1. 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.

Output

2. Implement the following recipe(algorithm) to find the grade of a student. Test your
program to determine whether it works well for 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”
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:

3. In the following code, write a function absolute(y) that takes a number as an argument,
calculates and returns the absolute value. The code should then print the absolute value
returned by the function The program should work correctly for any number entered by
the user. Don't use the built-in function abs( ).

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

Test Case 2: Output when absolute(0) is called

Test Case 3: Output when absolute(8) is called

4. Write a program which uses a single function foo(x) to print “positive” if the number x is
positive, print “zero” if the number x is a 0 and print “negative” if the number x is
negative. Note: foo() function should not return back anything.
5. Write a program which uses a single function x(y) which returns True if y is an integer, and it
is positive, and it is even (all 3 must be True), and returns False otherwise. The returned value should
then be printed at the output. Draw a flow chart first and then code.
Test Case 1: Output when x(0) is called

Test Case 1: Output when x(-4) is called

Test Case 1: Output when x(4) is called

6. Write a function r() which takes three arguments. The first argument is the boolean
operation ( consider AND and NAND operations only ) while the rest of the two
arguments are the operands ( consider True / False only ) on which the boolean
operation is to be applied. The function r() should return the result ( in the form of True
or False ) of the boolean operation which should then be printed at the output

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

Test Case 2: Output when r(“nand”,True,True ) is called


7. Determine the output of the following codes without using a computer. What is the value
of x when Code 1 and 2 run completely?
Code 1 Code 2 Code 3 (Nested If-Else)

Code 4
Code 5 (The ‘return’ conundrum)
Experiment # 4
Implementation of Non-Nested Loops in
Python
Note: Draw a flowchart before coding question number 5 to 8.
1. 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.

Test case 1:

Test case 2:

Test case 3:
2. 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.
B. Now put the code you wrote in part A into the function f(name) shown below. The argument of
the function f() could be any name.

Test case 1: The following output comes when f(“ali”) is called

Test case 2: The following output comes when f(“cat”) is called

C. Now add another parameter ‘n’ to the function f(name) to print the name ‘n’ times. For
example f(“ali”, 3) should print ‘ali’ 3 times. Another example: f(“yahya”, 10) should print yahya 10 times.
Submit part C code only by the name e4t2.py.

Test case 1: The following output comes when f(“ail” , 5) is called


Test case 2: The following output comes when f(“Parrot”,3) is called

Notice how we approached this problem of writing a complete function. First we wrote code without any
user-defined function in part A. Then we wrote the code of part A inside the function f() (Part B). Then
we added a new parameter ‘n’ to the function. Follow this approach for writing functions!!!

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

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

Test case 2: The following output comes when print_even(3) 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

Test case 2: The following output comes when print_even(30) 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 6. For example when print_even(50) is called, the following output
should appear. Submit part D code only by the name e4t3.py

Test case 1: The following output comes when print_even(50) is called

Test case 2: The following output comes when print_even(30) is 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!!
4. 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
back anything.

Output

5. Steps a to e below are part of an algorithm (algo) to find the absolute of a number three
times. Do you think the program will work correctly or the order of the steps should be
rearranged to correctly run the program? If so, rearrange the steps below. Convert the
following algorithm into a flow chart. Then start to code.

Algorithm for question 5

Repeat the following steps a to c 3 times using a for-loop:

a. Display the message “The absolute of x is ___” where ___ is the absolute of x.
b. Prompt the user to enter the number, and store it in variable x.
c. Call the function absolute(x), which takes x as argument, to find and return the
absolute of x.

Write the following steps inside the definition of the function absolute(y). Do you
think the steps below need to be rearranged?

d. Return y
e. If y is negative, then multiply it by -1 and store it in y.
Test case 1:

Test case 2:

6. 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 as long as 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 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:

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


b. While iterating over variable s
If the character in s is 1, increase variable a by 1s
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 comes when a=”11112333”


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

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

Test Case 2: The following output comes when


getSecretMessage(“orupacrzypaomamhcyapwhhautatxtaeyearp”,”a”) is called
9. Determine the output of the following codes without using the computer. What does the
function mystery() do in code 3 ? Give answers on a piece of paper.

Code 1 Code 2 Code 3

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

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 no, 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 no, explain why not.
Experiment # 5
Formatting, Environment Diagram Involving
a Function and Debugging

First you have to do question no 2, 3, 9 and 10 of experiment 4 before starting this experiment.

1. Without using the computer


a. Draw, on your ITC Lab register, one environment diagram for code no. 1 when it is
completely executed.
b. Draw, on your ITC Lab register, one environment diagram for code no. 2 just before the
function double(3) returns its value.
c. Draw, on your ITC Lab register, one environment diagram for code no. 2 just before the
function hmm(wow) returns its value.
d. Draw, on your ITC Lab register, one environment diagram for code no. 2 after the code
runs completely.

Code 1 Code 2

2. Complete the following code using f-strings to get the output shown below. You are not allowed
to use space(s) inside the f-string at line no 12 to 14. Variables x and y have the percentage of ITC
and math respectively.
Output

Before doing questions 3 to 6, watch this video

3. The following code contains three errors. Copy the code from this file and paste into the coding
area of the Spyder software. Follow the steps below
a. Run the code and write the error message on your lab register. What do you understand
from the error message? Did the error message display the line number at which the
error is present? Correct this mistake.
b. Now run the code again and write the error message on your lab register. What do you
understand from the error message? Did the error message display the line number at
which the error is present? Correct this mistake.
c. Now run the code again and write the error message on your lab register. What do you
understand from the error message? Did the error message display the line number at
which the error is present? Correct this mistake.
d. Determine the output of the code, after removing the errors you caught in parts a to c,
without using the computer.
4. The function absolute(y) is supposed to return the absolute of a number. But upon running the code it
gives incorrect output. Follow the steps below to find the cause of the incorrect output

a. Go through the code step by step (known as code tracing) using a pen and a paper. Will
the code work for all numbers? If not, why? What is the problem?

b. Assume you were unable to go through the code (due to tiredness or

having watched maybe ) and spot the mistake using a pen and page. Use
pythontutor.com to trace the code step by step. Did each step run according to your
expectation? If not, which step(s) are causing incorrect output to appear. Give reasons.
c. What type of error the code contains - - - Syntax, Runtime or Logical. Give a reason.

5. The following code, when executed, gives incorrect output. Follow the steps below to correct the
code. Follow the steps below to find the cause of the incorrect output

a. Go through the code step by step (code tracing) using a pen and a paper and write the
output. Did you spot the mistake?
b. Assume you were unable to go through the code and spot the mistake using a pen and
page. Use pythontutor.com to trace the code step by step. Did each step run according
to your expectation? If not, which step(s) are causing incorrect output to appear. Give
reasons.
c. What type of error the code contains - - - Syntax, Runtime or Logical. Give a reason.
6. The following code is supposed to print the number of spaces in the password. Do you think the code
prints the correct number of spaces in the password? To answer this, follow the steps below.

a. Go through the code step by step (code tracing) using a pen and a page. What is the expected
output and what did you get actually?
b. Assume you were unable to go through the code and spot the mistake using a pen and page. Use
pythontutor.com to trace the code step by step. Did each step run according to your
expectation? If not, which step(s) are causing incorrect output to appear. Give reasons.
c. What type of error the code contains (if any) - - - Syntax, Runtime or Logical. Give a reason.

7. What lessons have you learnt by doing questions 4 to 6? Explain briefly.


Experiment # 6
Implementation of Nested Loops in Python
Draw flowchart for question 5 and 6.
1. Determine the output of the following code without using the computer.

2. Complete the following program to get the output as shown below.

Output
3. Convert the following flowchart to python code to get the output as shown below

Output
4. Using the algorithm shown below, write the function PrimeFactors(x) which takes a
positive integer x and prints all of its prime factors in a nice format. A prime factor is a
number that is both prime and evenly divides the original number (with 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 a 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
5. 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 Sample 1

Output Sample 2

6. 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 Sample 1

Output Sample 2
Experiment # 7
Implementation of Lambda Functions and Higher Order
Functions in Python
1. Determine the output of the following codes without using the computer. Code 2 and 3
could be traced without using the environment diagram.
For code 1
1. Draw the environment diagram when f(x+n) is about to be called at line 51. What will
be applied to (x+n) at line 51 i.e. what f is evaluated to at line 51?
2. When f(x+n) is called, what value of n will be used? Give reason
3. Draw the environment diagram when the computer is about to exit the function f(f,x)
after running it completely.
4. Draw a maximum of 4 environment diagrams which are created during the execution
of line 54.

Code 1 Code 2
2. 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:

l
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 upto n when summation(n,cube) is called, where n is
3 3 3
any integer. For example, summation(3,cube) should return 1 + 2 + 3 which is
36
● summation of natural integers upto n when summation(n,naturals) is called, where n
is any integer. For example, summation(3, naturals) should return 1 + 2 +3
which is 6.

3. 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. Note: Delete lines
89 to 91 before submitting the file.

4. Write a function make_keeper(n) that takes in a number n and returns a function f


that takes in a single parameter cond which is a user-defined function. When we pass
in cond into this returned function f, it will print out numbers from 1 to n if calling
cond on that number returns True. For example, calling make_keeper(6)(is_even)
should print all even numbers from 2 to 6. Note: Delete line 76 before submitting
the file.
5. 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 which takes a
number x as an argument and returns f(g(x)). Note: Delete line 14 and 16 before
submitting the code.

Challenge: Can you write only a single statement inside the compose function so
that it performs its required job!!
6. 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 returned function 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.
Lab # 8
Implementation of 1D and 2D Lists in Python
Note: If you are unsure anything related to PYTHON, then use this website https://docs.python.org/3/

1. Trace the following codes without using the computer. Draw the environment diagram
for code 1

Code 1 Code 2

Code 3

Code 4
2. 1D List: Write a program which calculates the sum of all the prices 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 the prices 40, 5.3, 7.8, and 1 stored in a list.

Test Case 1: The following output comes when price=[20.1, 3.2, 1.3, 2.3]

Test Case 2: The following output comes when price=[10, 5, 3, 2]

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
Test Case 1: The following output comes when getProvince(CitiesList,’Lahore’) is
called:

Test Case 2: The following output comes when getProvince(CitiesList,’Hyderabad’)


is called:

4. Implement the function couple, which takes in two lists and returns a list that
contains lists with i-th elements of two sequences coupled together. You can assume
the lengths of two sequences are the same. The code should work for any length of
list a or b

Test Case: The following output comes when couple( [10,20,30], [70,80,90] ) is called:

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


return the required list
5. 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.
Test Case 1: The following output comes when FindMultiples([11, 20, 35, 43, 50], 5)
is called:

Test Case 2: The following output comes when FindMultiples([44, 17, -77, 34, -95,
88], 11) is called:

6. A. 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 the list a. Note:
Don't make a new list to store the required list.
Test Case: The following output comes when a = [-3,5,-10,10]

B. Repeat part a for the 2D list shown below. The code should work correctly for any size of
the 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.

Test Case: The following output comes when a = [ [-3,5,-10,10], [-4, 2, -6] ]
7. 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'.
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

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 into 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
8. Code 2 and 3 in question 2, fail to remove 3 successfully from the list a. Write a code
using while-loop to remove 3 successfully.

9. Write a non-destructive function onlyPositive(L) that takes as input a 2D list L and


returns a new 1D list that contains only the positive elements of the original list, in
the order they originally occurred. You may assume the list only has numbers in it.
Example: onlyPositive( [ [1, 2, 3], [4, 5, 6] ] ) returns [1, 2, 3, 4, 5, 6],
onlyPositive( [ [0, 1, 2], [-2, -1, 0], [10, 9, -9] ] ) returns [1, 2, 10, 9], and
onlyPositive( [ [-4, -3], [-2, -1] ] ) returns [ ].
Lab # 9
Implementation of Recursion in Python
1. 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

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

3. A. Write a recursive function add(L) that takes a list L of numbers and returns the
sum of all the numbers in the list.
B. Solve the problem in part A using tree recursion i.e. divide the list into two
halves.
4. Write a 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].

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

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

7. 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 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.
Lab # 10
Implementation of Object Oriented Programming in Python
Note: To save time, copy paste the code given here
1. Determine the output of the following code without using the computer. For the
following code, which of the following expressions evaluates to an integer?
● b.z
● b.z.z
● b.z.z.z

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. Magic/Special Methods: 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


5. Complete the following code so that no “Assertion Error” message is displayed
when the code runs.
6. 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
7. 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.
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.
Lab # 11
Plotting Data in Python
Topics to be covered in this experiment
● Use MATPLOTLIB and NUMPY tools to create and plot the data.

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

2. 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, stop time, label and color
of the plot as inputs. Define another function SetPlot() to label the plot and display the
grid. 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/Second)
φ = Phase shift of the sine wave
t = time in seconds
Note: Python considers the units of the angle of the function sin() to be radians i.e.
sin(90) = 0.893 instead of sin(90) = 1.
Incomplete Code

Output

3. Write a program to display three sinusoidal waves in one figure as shown below. For this
purpose, define a function PrintSine() that takes the amplitude, frequency, phase shift,
stop time and label of the plot as inputs. 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/Second)
t = time in seconds
Output
4. 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
2 2 2
(𝑥 − 𝑎) + (𝑦 − 𝑏) = 𝑟

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
Lab # 12
Dictionaries in Python
1. Determine the output of the following program without using the computer.

2. Create a dictionary of 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

Lahore Punjab

Peshawar KPK

Karachi Sindh

Quetta Balochistan

Gilgit GB

Output

3. 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
4. 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

5. The fruits in a bag of groceries are provided as a list (eg. ["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:
Lab # 13
Data Science using Python
First update the PANDAS library by typing the following command in spyder console:

1. 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.
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.
● 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.
Lab # 14
Signal Manipulation & Processing in Python

You might also like