Python
Python
Id No.:20EC413
BACHELOR OF TECHNOLOGY
ELECTRONICS AND COMMUNICATION
1
20EC413
Certificate
2
20EC413
INDEX
Sr.No.
AIM Date Pg. Sign
Operations :
a) Write a program to compute distance between two points
taking input from the user (Pythagorean Theorem)
3.
b) Write a program add.py that takes 2 numbers as command
line arguments and prints its sum.
Control Flow :
a) Write a Program for checking whether the given number is
an even number or not.
b) Using a for loop, write a program that prints out the decimal
4. equivalents of 1/2, 1/3, 1/4, . . . ,1/10
c) Write a program using for loop that loops over a sequence.
What is sequence?
d) Write a program using a while loop that asks the user for a
number, and prints a countdown from that number to zero.
Control Flow – Continued :
a) Find the sum of all the primes below two million. Each new
term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10
5. terms will be: 1, 2, 3, 5,
8, 13, 21, 34, 55, 89,
b) By considering the terms in the Fibonacci sequence whose
values do not exceed four million, find the sum of the even
valued terms.
3
20EC413
Data Structures :
a) Write a program to count the numbers of characters in the
string and store them in a dictionary data structure
b) Write a program to use split and join methods in the string
and trace a birthday with a dictionary data structure.
6. c) Write a program combine lists that combines these lists into
a dictionary.
d) Write a program to count frequency of characters in a given
file. Can you use character frequency to tell whether the
given file is a Python program file, C program file or a text
file?
Files :
a) Write a program to print each line of a file in reverse order.
7.
b) Write a program to compute the number of characters, words
and lines in a file.
Functions:
a) Write a function ball collides that takes two balls as
Parameters and computes if they are colliding. Your
8. function should return a
Boolean representing whether or not the balls are colliding
b) Write a function to find mean, median, mode for the given
set of numbers in a list.
Functions – Continued :
a) Write a function nearly equal to test whether two strings
are nearly equal. Two strings a and b are nearly equal when
9. a can be generated by a single mutation on b.
b) Write a function dup to find all duplicates in the list.
c) Write a function unique to find all the unique elements of a
list.
4
20EC413
Multi-D Lists :
a) Write a program that defines a matrix and prints
b) Write a program to perform addition of two square
11.
matrices
c) Write a program to perform multiplication of two square
matrices
OOP :
Class variables and instance variable and illustration of the self -
12. variable
i. Robot
ii. ATM Machine
GUI , Graphics :
a) Write a GUI for an Expression Calculator using tk .
b) Write a program to implement the following figures using
turtle.
13.
5
20EC413
PRACTICAL-1
AIM: Program from HALTERMAN PYTHON BOOK
CHAPTER-2
LISTING 2.1
x=10
print(x)
OUTPUT:
LISTING 2.2
x=10
print('x = ' +str))
x = 20
print('x = ' +str))
x = 30
print('x = ' +str))
OUTPUT:
LISTING 2.3
6
20EC413
x = 10
print('x = ' + str(x))
x = 20
print('x = ' + str(x))
x = 30
print('x = ' + str(x))
OUTPUT:
LISTING 2.4
x,y,z = 100, -45, 0
print('x =', x, ' y=', y, ' z=', z)
OUTPUT:
7
20EC413
LISTING 2.5
a = 20
print('first, variable a has value', a, 'and type', type(a))
a = 'abc'
print('now, variable ahas value', a, 'and type', type(a))
OUTPUT:
LISTING 2.6
pi = 3.14159;
print("pi =", pi)
print("or", 3.14, "for short")
OUTPUT:
LISTING 2.7
avagadros_number = 6.022e23
c = 2.998e8
print("Avogadro's number =", avagadros_number)
print("Speed of light =", c)
8
20EC413
OUTPUT:
LISTING 2.8
print('A\nB\nC')
print('D\tE\tF')
print('wx\byz')
print('1\a2\a3\a4\a5\a6')
OUTPUT:
LISTING 2.9
print("Did you know that 'word is word?")
print('Did you know that "word" is word?')
print('Did you know that \'word\' is word?')
print("Did you know that \"word\" is word?")
9
20EC413
OUTPUT:
LISTING 2.10
filename = 'C:\\users\\rick'
print(filename)
OUTPUT:
LISTING 2.11
print('Please enter some text:')
x = input()
print('Text entered:', x)
print('Type:', type(x))
OUTPUT:
10
20EC413
LISTING 2.12
print('Please enter an integer value:')
x = input()
print('Please enter another integer value:')
y = input()
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)
OUTPUT:
LISTING 2.13
x = input('Please enter an integer value:')
y = input('Please enter another integer value:')
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)
OUTPUT:
11
20EC413
LISTING 2.14
num1 = int(input('Please enter an integer value: '))
num2 = int(input('Please enter another integer value: '))
print(num1, '+', num2, '=', num1 + num2)
OUTPUT:
LISTING 2.15
x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))
x2 = eval(input('Entry x2? '))
print('x2 =', x2, ' type:', type(x2))
x3 = eval(input('Entry x3? '))
print('x3 =', x3, ' type:', type(x3))
x4 = eval(input('Entry x4? '))
print('x4 =', x4, ' type:', type(x4))
12
20EC413
OUTPUT:
LISTING 2.16
num1, num2 = eval(input('Please enter number 1, number 2: '))
print(num1, '=', num2, '=', num1 + num2)
OUTPUT:
LISTING 2.17
print(eval(input()))
OUTPUT:
LISTING 2.18
print('A', end='')
print('B', end='')
print('C', end='')
13
20EC413
print()
print('X')
print('Y')
print('Z')
OUTPUT:
LISTING 2.19
w, x, y, z = 14, 15, 16, 17
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')
OUTPUT:
14
20EC413
CHAPTER-3
LISTING 3.1
value1 = eval(input('Please enter a number: '))
value2 = eval(input('Please enter another number: '))
sum = value1 + value2
print(value1, '+', value2, '=', sum)
OUTPUT:
LISTING 3.2
one = 1.0
one_third = 1.0/3.0
zero = one - one_third - one_third - one_third
print('one =', one, ' one_third =', one_third, ' zero =', zero)
OUTPUT:
15
20EC413
LISTING 3.3
one = 1.0
one_tenth = 1.0/10.0
zero = one - one_tenth - one_tenth - one_tenth \
- one_tenth - one_tenth - one_tenth \
- one_tenth - one_tenth - one_tenth \
- one_tenth
print('one =', one, ' one_tenth =', one_tenth, ' zero =', zero)
OUTPUT:
LISTING 3.4
#File dividedanger.py
#Get two integers from the user
dividend, divisor = eval(input('Please enter two numbers to divide: '))
#Divide them and report the result
print(dividend, '/', divisor, "=", dividend/divisor)
OUTPUT:
16
20EC413
LISTING 3.5
# Get a number from the user
value = eval(input('Please enter a number to cut in half: '))
# Report the result
print(value/2)
OUTPUT:
LISTING 3.6
degreesF = eval(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32);
print(degreesF, 'degrees F =', degreesC, 'degrees C')
OUTPUT:
LISTING 3.7
seconds = eval(input("Please enter the number of seconds:"))
hours = seconds // 3600 # 3600 seconds = 1 hours
seconds = seconds % 3600
minutes = seconds // 60 # 60 seconds = 1 minute
seconds = seconds % 60
17
20EC413
OUTPUT:
LISTING 3.8
seconds = eval(input("Please enter the number of seconds:"))
hours = seconds // 3600 # 3600 seconds = 1 hours
seconds = seconds % 3600
minutes = seconds // 60 # 60 seconds = 1 minute
seconds = seconds % 60
print(hours, ":", sep="", end="")
tens = minutes // 10
ones = minutes % 10
print(tens, ones, ":", sep="", end="")
tens = seconds // 10
ones = seconds % 10
print(tens, ones, sep ="")
OUTPUT:
LISTING 3.9
18
20EC413
Degrees F, degrees C = 0, 0
Degrees C = 5/9*(degrees F - 32)
Degrees F = eval(input('Enter the temperature in degrees F: '))
print(degrees F, 'degrees F =', degrees C, 'degrees C')
OUTPUT:
19
20EC413
CHAPTER-4
LISTING 4.1
a =True
b =False
print('a=', a,'b=', b)
a =False;
print('a=', a,'b=', b)
OUTPUT:
LISTING 4.2
dividend, divisor = eval(input('Please enter two numbers to divide:'))
If divisor != 0:
print(dividend,'/', divisor,"=", dividend/divisor)
OUTPUT:
LISTING 4.3
dividend, divisor = eval(input('Please enter two numbers to divide:'))
If divisor != 0:
20
20EC413
quotient = dividend/divisor
print(dividend,'/', divisor,"=", quotient)
print('Program finished')
OUTPUT:
LISTING 4.5
dividend, divisor = eval(input('Please enter two numbers to divide:'))
If divisor != 0:
print(dividend,'/', divisor,"=", dividend/divisor)
else:
print('Division by zero is not allowed')
OUTPUT:
LISTING 4.6
d1 = 1.11 - 1.10
d2 = 2.11 - 2.10
print('d1=', d1,'d2=', d2)
ifd1 == d2:
21
20EC413
print('Same')
else:
print('Different')
OUTPUT:
LISTING 4.9
value = eval (input ("Please enter an integer value in the range 0...10:")
if value >= 0:
If value <= 10:
print (value, "is in range")
else:
print (value, "is too large")
else:
print (value, "is too small")
Print ("Done")
OUTPUT:
LISTING 4.15
dividend, divisor = eval(input('Enter dividend, divisor: '))
msg = dividend/divisor
22
20EC413
if divisor != 0
else 'Error, cannot divide by zero'
print(msg)
OUTPUT:
LISTING 4.16
n = eval(input("Enter a number: "))
print('|', n, '| = ', (-n if n < 0 else n), sep='')
OUTPUT:
23
20EC413
PRACTICAL - 2
AIM: Write a program on Python Lists, Tuples, Sets, & Dictionaries.
Python Lists:
Ex 1:
fruits = ["apple", "banana", "cherry"]
print(fruits[1])
OUTPUT:
Ex 2:
fruits = ["apple", "banana", "cherry"]
fruits[0] = "kiwi"
OUTPUT:
Ex 3:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
OUTPUT:
24
20EC413
Ex 5:
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
OUTPUT:
Ex 6:
fruits = ["apple", "banana", "cherry"]
print(fruits[-1])
OUTPUT:
Ex 7:
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:5])
OUTPUT:
Ex 8:
fruits = ["apple", "banana", "cherry"]
print(len(fruits))
25
20EC413
OUT PUT:
26
20EC413
Python Tuples:
Ex 1:
fruits = ("apple", "banana", "cherry")
print(fruits[0])
OUTPUT:
Ex 2:
fruits = ("apple", "banana", "cherry")
print(len(fruits))
OUTPUT:
Ex 3:
fruits = ("apple", "banana", "cherry")
print(fruits[-1])
OUTPUT:
Ex 4:
27
20EC413
OUTPUT:
28
20EC413
Python Sets:
Ex 1:
fruits = {"apple", "banana", "cherry"}
if "apple" in fruits:
print("Yes, apple is a fruit!")
OUTPUT:
Ex 2:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
OUTPUT:
Ex 3:
fruits = {"apple", "banana", "cherry"}
more_fruits = ["orange", "mango", "grapes"]
fruits.update(more_fruits)
OUTPUT:
Ex 4:
29
20EC413
OUTPUT:
Ex 5:
fruits.remove("banana")
fruits.discard("banana")
OUTPUT:
30
20EC413
Python Dictionaries:
Ex 1:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car.get("model"))
OUTPUT:
Ex 2:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["year"] = 2020
OUTPUT:
Ex 3:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["color"] = "red"
31
20EC413
OUTPUT:
Ex 4:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
OUTPUT:
Ex 5:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
OUTPUT:
32
20EC413
PRACTICAL:3(a)
AIM: Write a program to compute distance between two points taking Input from
the user (Pythagorean Theorem)
DESCRIPTION:
• The Pythagorean theorem is the basis for computing distance between two
points. Let (x1,y1) and (x2,y2) be the co-ordinates of points on xy-plane.
• To find the distance, we need to use the method sqrt(). This method is not
accessible directly, so we need to import math module and then we need to
call this method using math static object.To find the power of a number, we
need to use ** operator.we use split() method to splits a string into a list.
CODE:
import math
a=input("enter first coordinate: ")
p1 = a.split(",")
b=input("enter, second coordinate: ")
p2 = b.split(",")
distance = math.sqrt(((int(p1[0])-int (p2[0]))*2)+((int(p1[1])-int (p2[1]))*2))
print("distance between ", a, "and", b, "is", distance)
33
20EC413
Output:
Conclusion: We gets the knowledge on math functions and how the values are
passed from the command line.
34
20EC413
PRACTICAL:3(b)
AIM: Write a program add.py that takes 2 numbers as command line arguments
and prints its sum.
DESCRIPTION:
• Command line arguments are the arguments that are passed to the program
when the program is invoked for execution.
• The first argument is always script name and it is also being counted in
number of arguments. As the command line arguments are strings, here we
need to type-cast those arguments to the suitable type.
Code:
num1=float(input("enter 1st no."))
num2=float(input("enter second no"))
print (f" sum is {num1+num2}")
35
20EC413
Output:
Conclusion: We gets the knowledge on math functions and how the values are
passed from the command line.
36
20EC413
PRACTICAL:4(a)
AIM: Write a Program for checking whether the given number is a even number
or not.
DESCRIPTION:
• If a number is exactly divisible by 2(Remainder is 0) then it is said to be an
Even number otherwise, the number is said to be an Odd number. In Python,
We use modulus(%) operator to find the remainder. executed. We can use
if…else statement to check whether the number is even or odd.
if…else statement
is a two-way decision making statement that decides what to do when the condition
is true and what to do when the condition is false. The general form of if…else
statement is as follows:
if condition:
intended statement block for true condition
else:
intended statement block for false condition
Code:
a=int(input("enter the no.:"))
if (a % 2 == 0):
print("no. is even")
else:
print("no. is not even or is odd" )
37
20EC413
Output:
38
20EC413
PRACTICAL:4(b)
AIM: Using a for loop, write a program that prints out the decimal equivalents of
1/2, 1/3, 1/4, . . . ,1/10
DESCRIPTION:
• A loop statement allows us to execute a statement or group of statements
multiple times. We can use for loop to calculate the decimal equivalents of
given set of numbers.
• The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {}
CODE:
for x in range(2,11):
y=1/x
mydecimal="{}"
print (mydecimal.format(y))
39
20EC413
OUTPUT:
40
20EC413
PRACTICAL:4(c)
AIM: Write a program using for loop that loops over a sequence. What is
sequence?
DESCRIPTION:
• A Sequence is the generic form for an ordered set. There are several types of
sequences in Python. The following 3 are most important.
• Lists: There are the most versatile sequence type. The elements of a list can
be any object and lists are mutable.
• Tuples: These are like lists, But Tuples are immutable.
• Strings: These are a special type of sequence that can store only characters
and having special notations.
CODE:
mySeqCkt =["Shalini","20EC413", "BVM"]
for x in mySeqCkt:
print(x)
OUTPUT:
41
20EC413
PRACTICAL:4(d)
AIM: Write a program using a while loop that asks the user for a number, and
prints a countdown from that number to zero.
DESCRIPTION:
• A loop statement allows us to execute a statement or group of statements
multiple times. Here, We are using while loop.
while loop statement:
• It repeatedly executes a target statement as long as the given condition is
true. The general form while statement is as follows:
while expression:
statements(s)
Here, the statement(s) may be a single a statement or a block of statements. The
condition may be any expression, and is true for any non-zero value. The loop
iterates while the condition is true. When the condition becomes false, program
control passes to the line immediately following the loop.
CODE:
N=int(input("enter the num: "))
while (N>=0):
print (N)
N-=1
42
20EC413
OUTPUT:
43
20EC413
PRACTICAL:5(a)
AIM: Find the sum of all the primes below two million. Each new term in the
Fibonacci sequence is generated by adding the previous two terms. By starting
with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
DESCRIPTION:
• A Prime number is a natural number greater than 1 that has no positive
divisors other than 1 and itself. A natural number greater than 1 and that is
not a prime number is called a composite number. Here, We are using a
while loop.
CODE:
flag = 200
i=2
sum = 0
counter = 0
while(i != flag):
for j in range(2, i + 1):
if i % j == 0:
counter += 1
if counter == 1:
sum+=i
counter = 0
i += 1;
print("The result is :",sum)
44
20EC413
OUTPUT:
45
20EC413
PRACTICAL:5(b)
AIM: By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
DESCRIPTION:
• The Fibonacci sequence is a series of numbers where a number is found by
adding up the two numbers before it. Starting with 0 and 1, the series will be
0,1,1,2,3,5,8,13 and so forth. In mathematical terms, the sequence Fn of
Fibonacci numbers is defined by the Recurrence relation.
Fn = Fn -1 + Fn –2
With initial values F0 = 0 and F1 = 1
CODE:
flag = 100 # Setting the number of the iteration.
a=1
b=2
temp = 0
print("The Fibonacci sequence is :")
print("\n",a," \n",b)
while(flag>=0):
temp = a + b
a =b
b = temp
flag = flag - 1
print(" \n",temp)
46
20EC413
OUTPUT:
47
20EC413
PRACTICAL:6(a)
AIM: Write a program to count the numbers of characters in the string and store
them in a dictionary data structure.
DESCRIPTION:
• Traverse each character in the string and its occurrence is stored in the
dictionary. Here, we are using a String and a Dictionary
String:
A String is a sequence of characters. Strings can be created by enclosing characters
inside a single quote or double quotes. Even triple quotes can be used in Python
but generally used to represent multiline strings and docstrings.
Dictionary:
The dictionary is Python's built-in mapping type. Dictionaries map keys to values
and these pairs provide a useful way to store data in python. The only way to
access the value part of the dictionary is by using the key.
CODE:
string=input('Enter string whose characters is to be count: ')
dic={}
dic.update({string:len(string)})
print(dic)
OUTPUT:
48
20EC413
PRACTICAL:6(b)
AIM: Write a program to use split and join methods in the string and trace a
birthday with a dictionary data structure.
DESCRIPTION:
• Compare the entered birthdate with each and every person‟s date of birth in
the dictionary and check whether the entered birthdate is present in the
dictionary or not. Here, We are using two built-in methods of the string:
split() and join().
• split():
This method breaks up a string using the specified separator and returns a
list of strings. The general form of split() is as follows:
str.split(separator)
• join():
This method provides a flexible way to concatenate a string. This method
returns a string in which the string elements of a sequence have been joined
by „sep‟ separator. The general form of join() is as follows:
sep.join(sequence)
CODE:
bdayin=input("enter the birth date:")
bdaylist=bdayin.split("/")
bday='-'.join(bdaylist)
mybday={"birthday": bday}
if 'birthday' in mybday:
print (mybday['birthday'])
49
20EC413
OUTPUT:
50
20EC413
PRACTICAL:6(c)
AIM: Write a program to use split and join methods in the string and trace a
birthday with a dictionary data structure.
DESCRIPTION:
• Python offers a range of compound data types often referred to as
Sequences. List is one of the most frequently used and very versatile data
type used in Python.
CODE:
def test(keys, values):
return dict(zip(keys, values))
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = [1, 2, 3, 4, 5]
print("Original lists:")
print(l1)
print(l2)
print("\nCombine the values of the said two lists into a dictionary:")
print(test(l1, l2))
51
20EC413
OUTPUT:
52
20EC413
PRACTICAL:6(d)
AIM: Write a program to count frequency of characters in a given file. Can you
use character frequency to tell whether the given file is a Python program file, C
program file or a text file?
DESCRIPTION:
• Opening a file refers to getting the file ready either for reading or for
writing. This can be done using the open () function.
• This function returns a file object and takes two arguments, one that accepts
the file name and another that accepts the mode (Access Mode).
• The file should exist in the same directory as the Python script, otherwise the
full address of the file should be written.
• Given a string, the task is to find the frequencies of all the characters in that
string and return a dictionary with key as the character and its value as its
frequency in the given string.
• Simply iterate through the string and form a key in dictionary of newly
occurred element or if element is already occurred, increase its value by 1.
CODE:
string = input("Enter a string :")
freq = [None] * len(string);
for i in range(0,len(string)):
freq[i] = 1;
for j in range(i+1, len(string)):
if(string[i] == string[j]):
freq[i] = freq[i] + 1;
53
20EC413
OUTPUT:
54
20EC413
PRACTICAL:7(a)
AIM: Write a program to print each line of a file in reverse order.
DESCRIPTION:
• Opening a file refers to getting the file ready either for reading or for
writing. This can be done using the open() function.
• The rstrip() method removes any trailing characters (characters at the end a
string, space is the default trailing character to remove.
CODE:
f=input("Enter file name: ")
for line in reversed(list (open(f))):
print(line.rstrip())
OUTPUT:
CONCLUSION Student gets the knowledge on basic concepts of files and lists.
55
20EC413
PRACTICAL:7(b)
AIM: Write a program to compute the number of characters, words and lines in a
file.
DESCRIPTION:
• Traverse each character in the file so that we can find number of characters,
words and lines in a text file. Here, We are using the some of the basic
methods of files.
• We already discussed about open() and close() in the previous programs.
read():
• If we need to extract string that contains all characters in the file, We can use
read(). The Syntax for read() in Python is:
str = file_object.read()
CODE:
f = open("my.txt", "r")
Number_of_lines = 0
Number_of_words = 0
Number_of_characters = 0
for line in f:
line = line.strip("\n")
words = line.split()
Number_of_lines += 1
Number_of_words += len(words)
number_of_characters += len(line)
f.close()
56
20EC413
OUTPUT:
CONCLUSION Student gets the knowledge on basic concepts of files and lists.
57
20EC413
PRACTICAL:8(a)
AIM: Write a function ball_collide that takes two balls as parameters and
computes if they are colliding. Your function should return a Boolean representing
whether or not the balls are colliding.
DESCRIPTION:
• A ball on a plane is a tuple of (x, y, r), r being the radius.
• If (distance between two balls centers) <= (sum of their radii) then (they are
colliding)
CODE:
import math
dist=math.sqrt((x2-x1)**2+(y2-y1)**2);
print("Distance b/w two balls: ",dist)
center=dist/2;
print("Collision point", center);
r=r1+r2;
print("Sum of radious",r)
58
20EC413
if(center<=r):
return True;
else:
print("Not Colliding")
return False;
c=ball_collide (4,4,3,2,2,3)
print(c)
print(c)
c=ball_collide (100, 200, 20, 200, 100,10)
OUTPUT:
59
20EC413
PRACTICAL:8(b)
AIM: Find mean, median, mode for the given set of numbers in a list.
DESCRIPTION:
Mean: The mean is the average of all numbers and is sometimes called the
arithmetic mean.
Median: The median is the middle number in a group of numbers.
Mode: The mode is the number that occurs most often within a set of numbers.
CODE:
import statistics
a = [11,10,50,70,80,55,66,74,78,55,87,98,95,70]
z = statistics.mode(a) #for mode
x = statistics.mean(a) #for mean
y = statistics.median(a) #for median
print("mean",x, "median = ", y,"mode = ",z) #prints the result
OUTPUT:
60
20EC413
PRACTICAL:9(a)
AIM: Write a function nearly equal to test whether two strings are nearly equal.
Two strings a and b are nearly equal when a can be generated by a single mutation
on b.
DESCRIPTION:
• Two strings are said to be nearly equal if a single mutation applied to one
string will result in another string. That means, Given two strings s1 and s2,
find if s1 can be converted to s2 with exactly one edit(mutation).
• If yes, then the function should return a True value as the result. Otherwise,
it must return a False value as the result.
CODE:
def nearly_equal(a,b):
#case 1 : one character less or more
if abs(len(a)-len(b))>1:
return False
if len(a)<len(b):
k = len(a)
else:
k = len(b)
if(len(a)!=len(b)):
for i in range(0,k):
if a[i] != b[i]:
return False
if(len(a)==len(b)):
count = 0
for i in range(0,len(a)):
61
20EC413
if a[i]!=b[i]:
count+=1 #print(count)
if count>1:
return False
return True
a = input()
b = input()
if (nearly_equal(a,b) == True ):
print("Nearly equal")
else:
print("Not Nearly equal")
k = nearly_equal(a,b)
OUTPUT:
62
20EC413
PRACTICAL:9(b)
AIM: Write a function dup to find all duplicates in the list.
DESCRIPTION:
• We need to write a function dups to find all duplicate elements in the list.
• If an element is repeated more than once in the list, then add that repeated
element to the resultant list.
CODE:
lst = [ 1,2,3,4,3,5,15,6,4,7,8,8]
dupitems = []
uniqitems={}
for x in lst:
if x not in uniqitems: uniqitems[x] = 1
else:
if uniqitems[x] == 1:
dupitems.append(x)
uniqitems[x] += 1
print("original List is")
print(lst)
print("Duplicate items")
print(dupitems)
63
20EC413
OUTPUT:
64
20EC413
PRACTICAL:9(c)
AIM: Write a function unique to find all the unique elements of a list.
DESCRIPTION:
• We need to write a function unique to find all unique elements in the list.
• If an element is found only once in the list, then add that element to the
resultant list.
CODE:
def unique(lst):
return list(set(lst))
my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique_list = unique(my_list)
print(unique_list) # Output: [1, 2, 3, 4, 5]
OUTPUT:
65
20EC413
PRACTICAL:10(a)
AIM: Write a function cumulative_product to compute cumulative product of a list
of numbers.
DESCRIPTION:
• We need to write a function cumulative_product to find cumulative product
of numbers in the list. A Cumulative product is a sequence of partial
products of a given sequence.
• For example, The cumulative product of sequence [a,b,c,…..] are
a,ab,abc,…..
CODE:
def cumulative_product(numlist):
product=1
cp=[]
for ele in numlist: product=product*ele cp.append(product)
return cp
numlist=[]
n=int(input("Enter number of elements to be insert:"))
for i in range(n):
ele=int(input("Enter element:")) numlist.append(ele)
cp=cumulative_product(numlist)
print("Cumulative product of list elements is ",cp)
66
20EC413
OUTPUT:
67
20EC413
PRACTICAL:10(b)
AIM: Write a function reverse to reverse a list. Without using the reverse function.
DESCRIPTION:
• We need to write a function reverse to reverse the given elements in a list.
• Reversing of a list is done by using the feature called slicing.
• Python‟s list objects have an interesting feature called slicing.
• We can view it as an extension of the square brackets indexing syntax. It
includes a special case where slicing a list with “[::-1]” produces a reversed
copy.
CODE:
def reverse(numlist):
i=0
j=len(numlist)-1
while(i<=j):
temp=numlist[i]
numlist[i]=numlist[j]
numlist[j]=temp
i=i+1
j=j-1
return numlist
numlist=[]
n=int(input("Enter number of elements to be insert:"))
for i in range(n):
ele=int(input("Enter element:"))
numlist.append(ele)
68
20EC413
reverse(numlist)
print("After reverse list elements are:\n",numlist)
OUTPUT:
CONCLUSION We get knowledge on functions & lists Without using the reverse
function.
69
20EC413
PRACTICAL:10(c)
AIM: Write function to compute gcd, lcm of two numbers. Each function
shouldn’t exceed one line
DESCRIPTION:
• We need to write a function to compute gcd, lcm of numbers. But here the
constraint is each function should not exceed one line. For this, we are using
lambda function.
lambda function:
• We can use lambda keyword to create small anonymous functions.
• Lambda functions can have any number of arguments but contain only one
expression.
• The expression is evaluated and returned.
• They cannot contain commands or multiple expressions.
• The general form of lambda function is as follows:
lambda arguments: expression
CODE:
gcd=lambda a,b: a if b==0 else gcd(b,a%b)
lcm=lambda a,b: (a*b)/gcd(a,b)
num1=int(input("Enter first number:")) #enter number 1
num2=int(input("Enter second number:")) #enter number 2
print("LCM of %d and %d is %d"%(num1,num2,lcm(num1,num2))) #prints lcm
print("GCD of %d and %d is %d"%(num1,num2,gcd(num1,num2))) #prints gcd
70
20EC413
OUTPUT:
71
20EC413
PRACTICAL:11(a)
AIM: Write a program that defines a matrix and prints
DESCRIPTION:
• A matrix is a two-dimensional data structure. In python, matrix is a nested
list.
• A list is created by placing all the items (elements) inside a square bracket [],
separated by commas.
Accessing the elements of a matrix:
• Similar to list we can access elements of a matrix by using square brackets []
after the variable like a[row-number] [col_number].
CODE:
R = int (input ("Enter the number of rows:"))
C = int (input ("Enter the number of columns:"))
# Initialize matrix
matrix = []
print ("Enter the entries rowwise:")
# For user input
for i in range(R): # A for loop for row entries
a = []
for j in range(C): # A for loop for column entries
a.append(int (input ()))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
72
20EC413
print ()
OUTPUT:
73
20EC413
PRACTICAL:11(b)
AIM: Write a program to perform addition of two square matrices.
DESCRIPTION:
• In order to perform addition of two matrices, the two matrices must have
same number of rows and same number of columns.
• We should use nested for loops to iterate through each row and each column.
• At each point, we add the corresponding elements in the two matrices and
store it in the result.
CODE:
# 1st matrix
matrix_1 = []
print("Enter the entries rowwise for 3x3:")
# For user input
for i in range(3): # A for loop for row entries
a =[]
for j in range(3): # A for loop for column entries
a.append(int(input()))
matrix_1.append(a)
# For printing the matrix
for i in range(3):
for j in range(3):
print(matrix_1[i][j], end = " ")
print()
# 2nd matrix
matrix_2 = []
74
20EC413
75
20EC413
OUTPUT:
76
20EC413
PRACTICAL:11(c)
AIM: Write a program to perform multiplication of two square matrices
DESCRIPTION:
• In order to perform multiplication of two matrices, then the number of
columns in first matrix should be equal to the number of rows in second
matrix.
• When we multiply two matrices by each other, the resulting matrix will have
as many columns as the biggest matrix in the equation.
• For example, If we are multiplying a 3*3 by a 3*4 matrix, the resulting
matrix will be a 3*4.
CODE:
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# 1st matrix
A = []
print("Enter the entries rowwise for 3x3:") # For user input
for i in range(3): # A for loop for row entries
a =[]
for j in range(3): # A for loop for column entries
a.append(int(input()))
A. append(a)
# For printing the matrix
for i in range(3):
for j in range(3):
print(A[i][j], end = " ")
print()
77
20EC413
# 2nd matrix
B = []
print("Enter the entries rowwise for 3x3:")
# For user input
for i in range(3): # A for loop for row entries
a =[]
for j in range(3): # A for loop for column entries
a.append(int(input()))
B. append(a)
# For printing the matrix
for i in range(3):
for j in range(3):
print(B[i][j], end = " ")
print()
# iterating by row of A
for i in range(len(A)):
# iterating by coloum by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
78
20EC413
OUTPUT:
79
20EC413
PRACTICAL:12(a)
AIM: Class variables and instance variables and illustration of the self - variable i)
Robot ii) ATM Machine
DESCRIPTION:
• Class variable: A variable that is shared by all instances of a class. Class
variables are defined within a class but outside any of the class's methods.
Class variables are not used as frequently as instance variables are.
• Instance variable: A variable that is defined inside a method and belongs
only to the current instance of a class.
• Self-variable: The first argument to every method inside a class is a special
variable self.
• Every time a class refers to one of its variables or methods, it must precede
them by itself.
• The purpose of self is to distinguish class‟s variables and methods from
other variables and functions in the program.
• For implementing Class Robot, a class variable called count, instance
variable called name and self variable self is used.
• To distinguish their usage, class variables are accessed using classname with
dot(.) operator.
• Where as, instance variables are accessed using self with dot(.) operator.
• For implementing Class ATM Machine, an instance variable called balance
and self variable self is used to call the instance variable within the method
of a class.
CODE:
Code(i):
class Robot:
population = 0
def __init__(self, name):
self.name = name
80
20EC413
print('(Initializing {0})'.format(self.name))
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working.'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot.
Yeah, they can do that.'''
def howMany():
'''Prints the current population.'''
droid1 = Robot('R2-D2')
81
20EC413
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy them.")
del droid1
del droid2
Robot.howMany()
Output(i):
Code(ii):
import random class Account:
# Construct an Account object
def init (self, id, balance = 0, annualInterestRate = 3.4): self.id = id
self.balance = balance self.annualInterestRate = annualInterestRate
def getId(self): return self.id
def getBalance(self): return self.balance
82
20EC413
83
20EC413
84
20EC413
Output(ii):
85
20EC413
PRACTICAL-13(A)
Program:
86
20EC413
87
20EC413
minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = " #eee", cursor =
"hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx =
1, pady = 1) # fourth row one = But-
ton(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2",
command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1
)
two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1
)
three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = " #fff", cursor =
"hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1
, pady = 1) plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg =
"#eee", cursor = "hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady
=
1)
# fourth row zero = But- ton(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg =
"#fff", cur- sor = "hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, column- span = 2,
padx = 1, pady = 1)
point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = " #eee", cursor =
"hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx =
1, pady = 1)
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor =
"hand2", command = lambda: bt_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)
win.mainloop()
88
20EC413
OUTPUT :
89
20EC413
PRACTICAL-13(B)
CODE :
colors =["red", "green", "blue", "orange", "purple","pink", "yellow"]
painter = turtle.Turtle()
painter.pensize(3)
for i in range(10):
color =random.choice(colors)
90
20EC413
painter.pencolor (color)
painter.circle(100)
painter.right (30)
painter.left(60)
painter.setposition(0,0)
OUTPUT :
91
20EC413
CODE(II) :
import turtle
window = turtle.Screen()
painter = turtle.Turtle()
window.bgcolor("lightgreen")
painter.fillcolor('blue')
painter.pencolor('blue')
painter.pensize(3)
def drawsq(t, s):
for i in range(4):
t.forward(s)
t.left(90)
for i in range(1,180):
painter.left(18)
drawsq(painter, 200)
92
20EC413
OUTPUT :
93