6CS4-23 Python Lab
6CS4-23 Python Lab
3 Write a Program for checking whether the given number is an even 17/02/2020
4.
number or not.
Using a for loop, write a program that prints out the decimal 17/02/2020
5.
equivalents of 1/2, 1/3, 1/4, . . . , 1/10 4
7. Write a program using for loop that loops over a sequence. 02/03/2020
Write a program using a while loop that asks the user for a number, 02/03/2020
8.
and prints a countdown from that number to zero.
9. Find the sum of all the primes below two million. 02/03/2020
Write a program to use split and join methods in the string and trace a
12.
birthday of a person with a dictionary data structure
Write a function nearly equal to test whether two strings are nearly
16. equal. Two strings a and b are nearly equal when a can be generated
by a single mutation on.
b=1.7
print(type(b))
c="Akhil"
print(type(c))
d=1j
print(type(d))
e=[1,2,3]
print(type(e))
f=(1,2,3)
print(type(f))
g=range(6)
print(type(g))
h={"name":"Akhil", "Age":26}
print(type(h))
i={"John","Marry"}
print(type(i))
j=frozenset({"Akhil","Addi","Divi"})
print(type(j))
k=True
print(type(k))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
Note:
Difference between set and frozen set:
Frozen set is just an immutable version of a Python set object. While elements of a set can
be modified at any time, elements of frozen set remain the same after creation.
Due to this, frozen sets can be used as key in Dictionary or as element of another set. But like
sets, it is not ordered (the elements can be set at any index).
# random dictionary
person = {"name": "John", "age": 23, "sex": "male"}
fSet = frozenset(person)
print('The frozen set is:', fSet)
2. Write a program to compute distance between two points taking input from the user.
Formula:
Distance=√ ( x 2−x 1 )2 + ( y 2− y 1 )2
Program:
import math
print("Enter cordinates of first point: ")
x1=int(input("X1: "))
y1=int(input("Y1: "))
distance=math.sqrt((x2-x1)**2+(y2-y1)**2)
print(distance)
Output:
Enter cordinates of first point:
X1: 3
Y1: 2
Enter cordinates of second point:
X2: 7
Y2: 8
7.211102550927978
3. Write a program add.py that takes 2 numbers as command line arguments and prints its
sum.
Program:
%With 2 inputs only
import sys
x=int(sys.argv[1])
y=int(sys.argv[2])
sum=x+y
print(sum)
Output:
4. Write a Program for checking whether the given number is an even number or not.
Program:
while 1:
x=int(input("Enter Number: "))
if x%2:
print("ODD")
else:
print("EVEN")
y=(input("Do you want to continue y/n: "))
if y=="n":
break;
Output:
Enter Number: 2
EVEN
Do you want to continue y/n: y
Enter Number: 4
EVEN
Do you want to continue y/n: y
Enter Number: 5
ODD
Do you want to continue y/n: n
5. Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, . . . , 1/10
Program:
x=1
for y in range(11):
if y!=0 and y!=1:
print(x/int(y))
Output:
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
0.1111111111111111
0.1
6. Write a Program to demonstrate list and tuple in python.
List is a collection which is ordered and changeable. It also allows duplicate values.
Program:
#Creating List
mylist=["BMW","Farari","Toyota"]
print("Printing all items of a list: ",mylist)
#Clear list
mylist.clear()
print("List is now empty: ",mylist)
Output:
Printing all items of a list: ['BMW', 'Farari', 'Toyota']
Enter New Item: Tata
Printing updated list: ['BMW', 'Farari', 'Toyota', 'Tata']
Enter New Item: Mahindra
Printing updated list: ['BMW', 'Mahindra', 'Farari', 'Toyota', 'Tata']
Enter Item You Want To Remove: Farari
Printing updated list: ['BMW', 'Mahindra', 'Toyota', 'Tata']
New list is ['BMW', 'Mahindra', 'Toyota', 'Tata']
List is now empty: []
Tuple is a collection which is ordered and unchangeable. It also allows duplicate values.
Program:
#Creating tuple
mytuple=("BMW","Farari","Toyota")
print("Printing all items of a tuple: ",mytuple)
#Add 2 tuples
newtuple=(1,2,3,4,2,5)
final=mytuple+newtuple
print("Tuple affter addition: ",final)
for i in range(1,11):
print(n," * ", i," = ",i*n)
Output:
Enter Number: 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
8. Write a program using a while loop that asks the user for a number, and prints a countdown
from that number to zero.
Program:
import time
n=int(input("Enter Number: "))
while n:
print(n)
time.sleep(1)
n-=1
Output:
Enter Number: 5
5
4
3
2
1
9. Find the sum of all the primes below two million.
Program:
def Sieve(n):
# driver program
n = 2000000
print ("Following are the prime numbers smaller")
print ("than or equal to", n)
Sieve(n)
Output:
Following are the prime numbers smaller than or equal to 2000000
142913828922
10. By considering the terms in the Fibonacci sequence whose values do not exceed four million.
WAP to find the sum of the even-valued terms.
Program:
a, b = 0, 1
total = 0
while True:
a, b = b, a + b
if b >= 4000000:
break
if b % 2 == 0:
total += b
print(total)
Output:
Sum of all even terms till 4000000 = 4613732
11. Write a program to count the numbers of lower case and upper case characters in the string
and store them in a dictionary data structure.
Program:
string=input("Enter string: ")
characters={"Lower":0,"Upper":0}
for i in string:
if i.islower():
characters["Lower"]+=1
elif i.isupper():
characters["Upper"]+=1
print(characters)
Output:
Enter string: A Quick BROWN Fox 1234
{'Lower': 6, 'Upper': 8}
12. Write a program to use split and join methods in the string and trace a birthday of a person
with a dictionary data structure
Program:
x=input("Enter date month and year of birth: ")
date_list=x.split(' ')
print(date_list[1])
date_dict={"Date":" ","Month":" ","Year":" "}
date_dict["Date"]=date_list[0]
date_dict["Month"]=date_list[1]
date_dict["Year"]=date_list[2]
x="-".join(date_dict.values())
print(x)
Output:
Enter date month and year of birth: 23 October 1989
October
23-October-1989
13. 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?
14. Write a program to print each line of a file in reverse order.
Program:
with open('File1.txt','r') as f, open('output.txt', 'w') as fout:
fout.writelines(reversed(f.readlines()))
with open('output.txt','r') as f:
print(f.read())
Output:
This is line 4
This is line 3
This is line 2
This is line 1
Note:
Where File1.txt contains
This is line 1
This is line 2
This is line 3
This is line 4
15. Write a program to compute the number of characters, words and lines in a file.
Program:
#opening a file in read mode
with open('File1.txt','r') as f:
res=f.read()
#counting letters Frequency
mydict={i: res.count(i) for i in set(res)}
print("Frequency of characters present in the file = ",mydict)
#counting words
word=res.split()
print('No of words = ',len(word))
#counting lines
lines=res.split('\n')
print("No of Lines = ",len(lines))
#counting characters
print("No of characters = ",len(mydict))
Output:
Frequency of characters present in the file = {'#': 3, 'e': 5, 'k': 1, 'w': 3, '\n': 1, 'I': 1, 'i': 6,
'r': 1, ' ': 17, 'A': 1, 'p': 1, 'y': 3, 'h': 4, 'a': 7, 'L': 1, 'd': 1, 'f': 1, 's': 4, 't': 3, 'u': 1, '.': 2, 'l': 2,
'm': 3, 'n': 9, 'o': 2, 'H': 1, 'g': 2}
No of words = 19
No of Lines = 2
No of characters = 27
16. 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.
Program:
def isEditDistanceOne(s1, s2):
# Find lengths of given strings
m = len(s1)
n = len(s2)
i=0
j=0
while i < m and j < n:
# If current characters dont match
if s1[i] != s2[j]:
if count == 1:
return False
return count == 1
# Driver program
s1 = "gfg"
s2 = "gfds"
if isEditDistanceOne(s1, s2):
print("Yes")
else:
print("No")
Output:
No
17. Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed one
line.
Program: GCD
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
Program: LCM
a x b = LCM(a, b) * GCD (a, b)
LCM(a, b) = (a x b) / GCD(a, b)
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
Output:
LCM of 15 and 20 is 60
18. Write a program to implement Merge sort.
Program:
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
i=j=k=0
mylist=[21,12,34,43,15,36,52]
print("Before Sorting: ")
print(mylist)
print("After Sorting: ")
selection(mylist)
Output:
Before Sorting:
[21, 12, 34, 43, 15, 36, 52]
After Sorting:
[12, 15, 21, 34, 36, 43, 52]
def insertion(arr):
for i in range(1,len(arr)):
j=i-1
temp=arr[i]
while temp<arr[j] and j>=0:
arr[j+1]=arr[j]
j-=1
arr[j+1]=temp
print(arr)
mylist=[21,12,34,43,15,36,52]
print("Before Sorting: ")
print(mylist)
print("After Sorting: ")
insertion(mylist)
Output:
Before Sorting:
[21, 12, 34, 43, 15, 36, 52]
After Sorting:
[12, 15, 21, 34, 36, 43, 52]