0% found this document useful (0 votes)
16 views

python_rev

The document is a Python revision guide covering topics such as list comprehensions, shallow vs deep copy, classes and objects, and miscellaneous facts about Python. It includes syntax explanations, demonstrations, and a series of assignments for practical application. The assignments range from simple calculations to creating functions and data structures.

Uploaded by

Subhodeep Chanda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

python_rev

The document is a Python revision guide covering topics such as list comprehensions, shallow vs deep copy, classes and objects, and miscellaneous facts about Python. It includes syntax explanations, demonstrations, and a series of assignments for practical application. The assignments range from simple calculations to creating functions and data structures.

Uploaded by

Subhodeep Chanda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

PYTHON REVISION

1/20/2025‒1/21/2025

Subhodeep Chanda
Roll No: 122
UG 1 SEM 2 (NEP)
Paper Code: C1PH230212P

NotedELN v. 1.5.4 — (C) Daniel Wagenaar 2013–2024


Table of Contents

1/20/’25 LIST COMPREHENSIONS 1


1/21/’25 Shallow Copy VS Deep Copy 6
1/21/’25 Classes and Objects in Python 8
1/21/’25 Miscellaneous Facts 9
1/21/’25 ASSIGNMENTS 16

Subhodeep Chanda: PYTHON REVISION i


LIST COMPREHENSIONS 1/20/’25
(1/5)
List comprehension is basically creating lists based on existing
iterables. It can also be described as representing for and if
loops with a simpler and more appealing syntax. They are
relatively faster than for loops

Syntax:

newlist = [expression for item in iterable if condition = = true]

NOTE: the return value is a new list, leaving the old list
unchanged.

Demonstrations:

Subhodeep Chanda: PYTHON REVISION 1 >


LIST COMPREHENSIONS 1/20/’25
(2/5)
> sort() − arranges the elements of a list in ascending order by
default

Example:

We can also arrange the elements of a list in descending order


by using the following parameter: reverse = ’true’

Example:

Subhodeep Chanda: PYTHON REVISION 2 >


LIST COMPREHENSIONS 1/20/’25
(3/5)
> Demonstrating usage of several built in list functions:

append()

clear()

count()

Subhodeep Chanda: PYTHON REVISION 3 >


LIST COMPREHENSIONS 1/20/’25
(4/5)
> extend()

index()

insert()

1/21

pop()

Subhodeep Chanda: PYTHON REVISION 4 >


LIST COMPREHENSIONS 1/20/’25
(5/5)
> reverse()

____________________________________________________________

Subhodeep Chanda: PYTHON REVISION 5


Shallow Copy VS Deep Copy 1/21/’25
(1/2)
Shallow Copy:

Creates a new object, but references the same nested objects


as the original.
Changes to nested objects affect both the original and the
copy.

Demonstration:

Subhodeep Chanda: PYTHON REVISION 6 >


Shallow Copy VS Deep Copy 1/21/’25
(2/2)
> Deep Copy: Creates a new object and recursively copies all
nested objects, making them independent of the original.

Demonstration:

Subhodeep Chanda: PYTHON REVISION 7


Classes and Objects in Python 1/21/’25

In Python, classes are blueprints for creating objects. They


define a structure and behavior for the objects. An object is an
instance of a class that holds data (attributes) and behavior
(methods).

Here,
’Car’ is the class
my_car is an object of the class ’Car’
The ’start’ method is a behavior that can be called using the
object

Subhodeep Chanda: PYTHON REVISION 8


Miscellaneous Facts 1/21/’25
(1/7)
1. Using the reduce function
The reduce function applies a binary function (e.g., f(x, y))
cumulatively to the items of a sequence, reducing it to a single
value.
You can use either a lambda function or a regular function
with reduce.

Demonstration:

Subhodeep Chanda: PYTHON REVISION 9 >


Miscellaneous Facts 1/21/’25
(2/7)
> 2. Tuples are just like lists, except that they are immutable(no
append method) and must be enclosed within parenthesis.

Subhodeep Chanda: PYTHON REVISION 10 >


Miscellaneous Facts 1/21/’25
(3/7)
> 3. A set is an unordered collection of unique elements from a
list or a string. Flowerbrackets are used to denote a set. Sets
are used to eliminate duplicate entries. Set objects also
perform mathematical operations like tuple, string and list.

Subhodeep Chanda: PYTHON REVISION 11 >


Miscellaneous Facts 1/21/’25
(4/7)
>
4. A dictionary is an un-ordered set which can store values
against a key.An empty dictionary can be created using the
phrase d={}.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.

Subhodeep Chanda: PYTHON REVISION 12 >


Miscellaneous Facts 1/21/’25
(5/7)
>
5. Python supports recursive function definition

Subhodeep Chanda: PYTHON REVISION 13 >


Miscellaneous Facts 1/21/’25
(6/7)
>

6. Python functions can take default values for arguments, e.g


def f(a,b=10):return a+b can be called as f(2) or f(2,3) to return
12 and 5 respectively. Arguments with default values must
occur after the regular argument list.

Subhodeep Chanda: PYTHON REVISION 14 >


Miscellaneous Facts 1/21/’25
(7/7)
>

7. 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=(-1,-3)

Subhodeep Chanda: PYTHON REVISION 15


ASSIGNMENTS 1/21/’25
(1/14)
1. Write a program to print out the sum of a 5 digit number.
num = int(input("Enter a 5-digit number: "))
s=0
for digit in str(num):
s += int(digit)
print("The sum of the digits is:", s)

Subhodeep Chanda: PYTHON REVISION 16 >


ASSIGNMENTS 1/21/’25
(2/14)
> 2. 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.

>>> import turtle


>>> def polygon(length, num, color):
... turtle.color(color)
... turtle.begin_fill()
... for i in range(num):
... turtle.forward(length)
... turtle.left(360/num)
... turtle.end_fill()
...
>>> polygon(100,6,'red')

Subhodeep Chanda: PYTHON REVISION 17 >


ASSIGNMENTS 1/21/’25
(3/14)
>

Subhodeep Chanda: PYTHON REVISION 18 >


ASSIGNMENTS 1/21/’25
(4/14)
> 3. Use list comprehension to find the sum of the elements of a
list of integers

numbers = [1, 2, 3, 4, 5]
sum_of_elements = sum([x for x in numbers])
print("Sum of the elements:", sum_of_elements)

Subhodeep Chanda: PYTHON REVISION 19 >


ASSIGNMENTS 1/21/’25
(5/14)
> 4. Print a sequence of stars, 10 on the first, 9 on the second, . . .
. The sequence will
look like -
**********
*********
********
*******
******
*****
****
***
**

Subhodeep Chanda: PYTHON REVISION 20 >


ASSIGNMENTS 1/21/’25
(6/14)
> 5. Use the String padding functions to print a pyramid, like
*
***
*****
*******

Subhodeep Chanda: PYTHON REVISION 21 >


ASSIGNMENTS 1/21/’25
(7/14)
> 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.

# DNA string
dna = "gcatgactattccttgac"
# Method 1: Using negative indexing
sixth_start = dna[5]
sixth_end = dna[-6]
# Method 2: Without using negative indexing
length_dna = len(dna)
sixth_end_non_negative = dna[length_dna - 6]

print("6th base from the beginning (using indexing):",


sixth_start)
print("6th base from the end (using negative indexing):",
sixth_end)
print("6th base from the end (without negative indexing):",
sixth_end_non_negative)

Subhodeep Chanda: PYTHON REVISION 22 >


ASSIGNMENTS 1/21/’25
(8/14)
> 7. Read a list of numbers and find out the median of the
dataset without destroying the original list.

def find_median(data):
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 1:
return sorted_data[n // 2]
else:
mid1, mid2 = sorted_data[n // 2 - 1], sorted_data[n // 2]
return (mid1 + mid2) / 2

data = [12, 5, 8, 7, 15, 10, 3]


median = find_median(data)

print("Original list:", data)


print("Median of the dataset:", median)

Subhodeep Chanda: PYTHON REVISION 23 >


ASSIGNMENTS 1/21/’25
(9/14)
> 8. Print butterfly wings

def print_wing_pattern():
n = 10
for i in range(n, 0, -1):
left = '*' * i
spaces = ' ' * (2 * (n - i))
right = '*' * i
print(left + spaces + right)
print_wing_pattern()

Subhodeep Chanda: PYTHON REVISION 24 >


ASSIGNMENTS 1/21/’25
(10/14)
> 9. Input an list of floats. Then print out a list of reciprocals
using list comprehension.

float_list = list(map(float, input("Enter a list of floats separated


by spaces: ").split()))
reciprocals = [1.0 / x if x != 0 else None for x in float_list]
print("List of reciprocals:", reciprocals)

10. Generate a discrete random walk sequence (for, say 50


steps) on the canvas using the function ‘randint’ available in
the ‘random’ module.

Subhodeep Chanda: PYTHON REVISION 25 >


ASSIGNMENTS 1/21/’25
(11/14)
>

Subhodeep Chanda: PYTHON REVISION 26 >


ASSIGNMENTS 1/21/’25
(12/14)
> 11. Use the reduce function to calculate the Arithmatic,
Geometric and Harmonic Mean of a list of floats.

from functools import reduce


from math import prod

def calculate_means(numbers):
n = len(numbers)
if n == 0:
return None, None, None
arithmetic_mean = reduce(lambda x, y: x + y, numbers) / n
geometric_mean = prod(numbers) ** (1 / n)
harmonic_mean = n / reduce(lambda x, y: x + (1 / y), numbers,
0)

return arithmetic_mean, geometric_mean, harmonic_mean

numbers = list(map(float, input("Enter a list of floats separated


by spaces: ").split()))

arithmetic, geometric, harmonic = calculate_means(numbers)


print(f"Arithmetic Mean: {arithmetic}")
print(f"Geometric Mean: {geometric}")
print(f"Harmonic Mean: {harmonic}")

Subhodeep Chanda: PYTHON REVISION 27 >


ASSIGNMENTS 1/21/’25
(13/14)
>

12. Create a dictionary from a list having tuples as its elements.


Check what happensto each element of a tuple and comment
on which one becomes a key and which becomes a value.

Each tuple in the list is assumed to have exactly two


elements.

The first element of the tuple becomes the key.


The second element of the tuple becomes the value.

13. Create a dictionary using set comprehension, just like list


comprehension, where key:value are related by i:i+2, where i is
the iterator going from (0,5).

Subhodeep Chanda: PYTHON REVISION 28 >


ASSIGNMENTS 1/21/’25
(14/14)
>
14. 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):
if n <= 0:
return "Invalid input."
elif n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)

n = int(input("Enter the position n:"))


result = fib(n)
print(f"The {n}-th Fibonacci number is: {result}")

≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡

Subhodeep Chanda: PYTHON REVISION 29

You might also like