PYTHON REVISION
1/25/2025‒1/26/2025
PRAMANA KUNDU
Roll No - 154, Sem2
NEP1, Jan'25
NotedELN v. 1.5.230320 — (C) Daniel Wagenaar 2013–2023
Table of Contents
1/25/’25 FACTSHEET 1
1/25/’25 ASSIGNMENTS 10
1/26/’25 15
PRAMANA KUNDU: PYTHON REVISION i
FACTSHEET 1/25/’25
(1/9)
30. List comprehensions are ways of applying an operation to
all list members.
CODE
>>> l = [5,2,7]
>>> [3*x for x in l]
OUTPUT
31. List comprehensions can be used to choose a subset of list
members to which the operations are applied.
CODE
>>> lst = [4,7,11,10]
>>> [3*x for x in lst if x%2==0]
OUTPUT
PRAMANA KUNDU: PYTHON REVISION 1 >
FACTSHEET 1/25/’25
(2/9)
>
32. List comprehensions can be applied to two (or more) lists.
CODE
>>> a = [2,4,3,7]
>>> b = [5,1,6,8]
>>> [x+y for x in a for y in b]
OUTPUT
33. The function reduce(f,seq) returns a single value
constructed by applying the binary function f to first two items
of the sequence, then on the result and the next item, and so
on. The lambda construct is a way of defining a scratch
function for which we do not bother to assign a name. lambda
functions can have any number of arguments, but must return
only a single expression constructed out of its arguments. In
order for reduce to work, the lambda function must contain
two (only two) arguments. You can also use a regular function
in place of a lambda function.
CODE
PRAMANA KUNDU: PYTHON REVISION 2 >
FACTSHEET 1/25/’25
(3/9)
> >>> from functools import reduce
>>> a = [2,3,7,4]
>>> reduce((lambda x, y:x+y), a)
OUTPUT
CODE
>>> def add(x,y):
... return x+y
...
>>> sum = reduce(add,a)
>>> print(sum)
16
OUTPUT
34. Tuples are just like lists, except that they are immutable(no
append method) and must be enclosed within parenthesis.
PRAMANA KUNDU: PYTHON REVISION 3 >
FACTSHEET 1/25/’25
(4/9)
34. Tuples are just like lists, except that they are immutable(no
> append method) and must be enclosed within parenthesis.
CODE
>>> p = 4,6,2
>>> print(p)
OUTPUT
CODE
>>> x,y,z=p
>>> print('x=',x)
>>> print('y=',y)
>>> print('z=',z)
OUTPUT
PRAMANA KUNDU: PYTHON REVISION 4 >
FACTSHEET 1/25/’25
(5/9)
> 35. A set is an unordered collection of unique elements from a
list or a string. ! Flower brackets are used to denote a set e.g.
s={1,2,6,9} is a set.
36. Sets are used to eliminate duplicate entries.
37. Set objects also perform mathematical operations like
tuple, string and list.
38. A dictionary is an un-ordered set which can store values
against a key, e.g d={’Rim’:21,’Raj’:23} is a dictionary with key-
value pairs (Rim,21) and (Raj,23).
39. An empty dictionary can be created using the phrase d={}.
40. The Keys() method of a dictionary retrieves all the keys of a
dictionary object in an unsorted list. Key-value pairs can be
inserted in an existing dictionary using d[’Sid’]=22.
41. d[’Rim’] just returns the associated value ‘21’.
CODE
CODES AND OUTPUTS COMBINED 5 >
PRAMANA KUNDU: PYTHON REVISION
FOR THIS PART IN THE NEXT PAGE.
FACTSHEET 1/25/’25
(6/9)
> >>> d = {'Rini':21,'Raj':23}
>>> d['Sid']=24
>>> d['Sid']
OUTPUT
42. The get method for dictionaries is suitable when someone
needs to query about an inexistent key, so that
d.get(’Pathan’,10) will fetch ‘10’ even when no values are
listed for this key in the dictionary. Note that d.get(’Rim’,10)
will get ‘21’, as expected.
CODES AND OUTPUTS
43. The code help(dict) helps us find out all about list
operations.
44. Python supports recursive function definition.
PRAMANA KUNDU: PYTHON REVISION 6 >
FACTSHEET 1/25/’25
(7/9)
>
For definition of a factorial:
CODE
>>> def func(n):
... if n==1 or n==0:
... return 1
... else:
... return n*func(n-1)
...
OUTPUT
45. Python functions can take default values for arguments.
CODE
>>> def f(a,b=10):
... return a+b
...
PRAMANA KUNDU: PYTHON REVISION 7 >
FACTSHEET 1/25/’25
(8/9)
> OUTPUT
46. Python functions can take key-value pairs in the argument
list too.
CODE
>>> def fnc(x=2,y=3):
... return x+2*y
...
OUTPUT
47. Python functions can take an arbitary number of
arguments beyond the standard list. These functions are
defined using form f(x,y,*a). If you call this with f(2,3,-1,-3) the
function would internally make the assignments x->2,y->3,a=(-
PRAMANA KUNDU: PYTHON REVISION
1,-3). 8 >
47. Python functions can take an arbitary number of
arguments beyond the standard list. These functions are 1/25/’25
FACTSHEET
(9/9)
defined using form f(x,y,*a). If you call this with f(2,3,-1,-3) the
> function would internally make the assignments x->2,y->3,a=(-
1,-3).
THIS SCREENSHOT IS TO BE IGNORED
PRAMANA KUNDU: PYTHON REVISION 9
ASSIGNMENTS 1/25/’25
(1/5)
1. Define a function to draw any regular polygon on the canvas.
It should take two arguments: the length of a side and the
number of sides. Test it out for several polygons. Modify the
function to take in an optional color argument.
1/26 CODE
>>> import time
>>> from turtle import *
>>> reset()
>>> ht()
>>> import turtle
>>> c = str(input("select colour: "))
>>> turtle.color(c)
>>> n = int(input("number of sides: "))
>>> l = int(input("length of sides: "))
>>> def pol(n,l):
... for i in range(n):
... fd(l);rt(360/n)
...
>>> pol(n,l)
>>> time.sleep(20)
OUTPUT
select colour: red
number of sides: 5
PRAMANA KUNDU: PYTHON REVISION 10 >
ASSIGNMENTS 1/25/’25
(2/5)
> length of sides: 50
2. Write a program to print out the sum of a 5 digit number.
CODE
>>> num=input("Enter a 5 digit number: ")
>>> if len(num)==5 and num.isdigit():
... sum=sum(int(digit)for digit in num)
... print(f"the sum of the digits of {num} is {sum}")
...
OUTPUT
Enter a 5 digit number: 76543
3. Use list comprehension to find the sum of the elements of a
list of integers.
PRAMANA KUNDU: PYTHON REVISION 11 >
ASSIGNMENTS 1/25/’25
(3/5)
>
CODE
>>> n = [3,2,5,7,1]
>>> l = [x for x in n]
>>> sum = sum(l)
>>> print("Sum of the elements is:",sum)
OUTPUT
4. Print a sequence of stars, 10 on the first, 9 on the second, . . .
. The sequence will look like -
**********
*********
********
*******
******
*****
****
***
**
PRAMANA KUNDU: PYTHON REVISION 12 >
ASSIGNMENTS 1/25/’25
(4/5)
> CODE
>>> for i in range(10,1,-1):
... print("*"*i)
...
OUTPUT
5. Use the String padding functions to print a pyramid, like
*
***
*****
*******
CODE
>>>
>>> lines=4
>>> for i in range(1,lines+1):
... pyr="*"*(2*i-1)
PRAMANA KUNDU: PYTHON REVISION 13 >
... print(pyr)
...
>>>
>>> lines=4 1/25/’25
ASSIGNMENTS
>>> for i in range(1,lines+1): (5/5)
> ... pyr="*"*(2*i-1)
... print(pyr)
...
OUTPUT
PRAMANA KUNDU: PYTHON REVISION 14
Untitled 1/26/’25
(1/11)
6. A dna string is specified as ’gcatgactattccttgac’. What is the
6th base from the beginning?, from the end? Answer this
question both using negative indexing and also without
assuming negative indexing.
Using negative indexing:
CODE
>>> dna = "gcatgactattccttgac"
>>> six_start = dna[5]
>>> six_end = dna[-6]
>>> print("6th base from the start is: ",six_start)
>>> print("6th base from the end is: ",six_end)
OUTPUT
Without assuming negative indexing:
CODE
>>> l_dna=len(dna)
>>> end_six=dna[l_dna-6]
>>> print("6th base from the end: ", end_six)
PRAMANA KUNDU: PYTHON REVISION 15 >
Untitled 1/26/’25
(2/11)
>
OUTPUT
7. Read a list of numbers and find out the median of the
dataset without destroying the original list.
CODE
>>> def med(data):
... list = sorted(data)
... n = len(list)
... if n%2==1:
... return list[n//2]
... else:
... m1, m2= list[n//2-1], list[n//2]
... return(m1+m2)/2
...
>>> data = [5,3,8,11,7,6]
>>> median = med(data)
>>> print("given list:", data)
>>> print("median:",median)
PRAMANA KUNDU: PYTHON REVISION 16 >
Untitled 1/26/’25
(3/11)
> OUTPUT
8. Print butterfly wings, as shown
********** **********
********* *********
******** ********
******* *******
****** ******
***** *****
**** ****
*** ***
** **
CODE
>>> def pattern():
... n=10
... for i in range(n,0,-1):
... wing_l='*'*i
... gap=' '*(2*(n-i))
... wing_r='*'*i
... print(wing_l+gap+wing_r)
...
>>> pattern()
PRAMANA KUNDU: PYTHON REVISION 17 >
... gap=' '*(2*(n-i))
... wing_r='*'*i
... print(wing_l+gap+wing_r) 1/26/’25
Untitled
... (4/11)
> >>> pattern()
OUTPUT
9. Input an list of floats. Then print out a list of reciprocals
using list comprehension.
CODE
>>> l = list(map(float,input("Enter a list of floats: ").split()))
Enter a list of floats: 4.0 6.0 3.0 7.0 8.0
>>> recip = [1.0/x if x!=0 else none for x in l]
>>> print("reciprocals:", recip)
OUTPUT
Enter a list of floats: 4.0 6.0 3.0 7.0 8.0
reciprocals: [0.25, 0.16666666666666666,
0.3333333333333333, 0.14285714285714285, 0.125]
PRAMANA KUNDU: PYTHON REVISION 18 >
Untitled 1/26/’25
reciprocals: [0.25, 0.16666666666666666, (5/11)
> 0.3333333333333333, 0.14285714285714285, 0.125]
10. Generate a discrete random walk sequence (for, say 50
steps) on the canvas using the function ‘randint’ available in
the ‘random’ module.
CODE
>>> from turtle import *
>>> import random
>>> for i in range(50):
...
rt(random.randint(0,360));fd(20);rt(random.randint(0,360));
...
>>>
PRAMANA KUNDU: PYTHON REVISION 19 >
Untitled 1/26/’25
(6/11)
> OUTPUT
11. Use the reduce function to calculate the Arithmatic,
Geometric and Harmonic Mean of a list of floats.
CODE
>>> from functools import reduce
>>> from math import prod
>>> def mean(n):
... a=len(n)
... if a==0:
... return none,none,none
... ari_mean=reduce(lambda x,y:x+y,n)/a
... geo_mean=prod(n)**(1/a)
... har_mean=a/reduce(lambda
PRAMANA x,y:x+(1/y),n,0)
KUNDU: PYTHON REVISION 20 >
... return ari_mean,geo_mean,har_mean
...
>>> n=list(map(float,input("Enter a list of floats:").split()))
Enter a list of floats:4.0 2.0 5.0 8.0 7.0
... if a==0:
... return none,none,none
... ari_mean=reduce(lambda x,y:x+y,n)/a 1/26/’25
Untitled
... geo_mean=prod(n)**(1/a) (7/11)
> ... har_mean=a/reduce(lambda x,y:x+(1/y),n,0)
... return ari_mean,geo_mean,har_mean
...
>>> n=list(map(float,input("Enter a list of floats:").split()))
Enter a list of floats:4.0 2.0 5.0 8.0 7.0
>>> arithmetic, geometric, harmonic= mean(n)
>>> print(f"Arithmetic mean:{arithmetic}")
>>> print(f"Geometric mean:{geometric}")
>>> print(f"Harmonic mean:{harmonic}")
OUTPUT
Arithmetic mean:5.2
Geometric mean:4.677885674856041
Harmonic mean:4.105571847507332
12. Create two sets, s1 and s2 and check all the operations that
can be done on sets, like intersection (s1 & s2), union ( s1|s2 ),
difference ( s1-s2 ), testing if one is a subset of the other
(s1<=s2), join (s1 |=s2).
PRAMANA KUNDU: PYTHON REVISION 21 >
Untitled 1/26/’25
(8/11)
> CODE
>>> set1 = {3,6,5}
>>> set2 = {2,7,4}
>>> print("Union:", set1 | set2)
>>> print("Intersection:", set1 & set2)
>>> print("Difference:", set1 - set2)
>>> set1 = {3,6,5}
>>> set2 = {6,4,7}
>>> print("Is set1 a subset of set2
(set1<=set2):",set1<=set2)
>>> print("Is set2 a subset of set1
(set2<=set1):",set2<=set1)
>>> print("Updated set1 after join (set1 |= set2):", set1)
OUTPUT
Union: {3, 4, 5, 6, 7}
Intersection: {6}
Difference: {3, 5}
Is set1 a subset of set2 (set1<=set2): False
PRAMANA KUNDU: PYTHON REVISION 22 >
Untitled 1/26/’25
(9/11)
> Is set2 a subset of set1 (set2<=set1): False
Updated set1 after join (set1 |= set2): {3, 5, 6}
13. Create a dictionary from a list having tuples as its elements.
Check what happens to each element of a tuple and comment
on which one becomes a key and which becomes a value.
CODE
>>> tup_lst=[(1,'red'), (2,'blue'), (3,'green')]
>>> show=dict(tup_lst)
>>> print("Dictionary:", show)
OUTPUT:
The first element of the tuple becomes a key, and the second
one becomes the value.
14. Create a dictionary using set comprehension, just like list
comprehension, where key:value are related by i:i+2, where i is
the iteratorKUNDU:
PRAMANA going from (0,5).REVISION
PYTHON 23 >
14. Create a dictionary using set comprehension, just like1/26/’25
list
Untitled
comprehension, where key:value are related by i:i+2, where (10/11)
i is
> the iterator going from (0,5).
CODE
>>> dic = {i: i+2 for i in range(6)}
>>> print("Dictionary:",dic)
this
screen-
shot
is to
be
ignored.
OUTPUT
15. Define a recursive function fib which can calculate the nth
member of the Fibonacci sequence: f1 = 1, f2 = 1, fn = fn − 1 +
fn − 2 when n > 2.
>>> def fib(n):
PRAMANA KUNDU: PYTHON REVISION 24 >
Untitled 1/26/’25
(11/11)
> ... if n<=0:
... return "invalid"
... elif n==1 or n==2:
... return 1
... else:
... return fib(n-1)+fib(n-2)
...
>>> n = int(input("Enter term n:"))
>>> answer = fib(n)
>>> print(f"The {n}th Fibonacci number:{answer}")
OUTPUT
Enter term n:6
The 6th Fibonacci number:8
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
PRAMANA KUNDU: PYTHON REVISION 25