0% found this document useful (0 votes)
13 views20 pages

Python Programming Practical Exercises

Practical File For RGPV

Uploaded by

ankitas5912
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views20 pages

Python Programming Practical Exercises

Practical File For RGPV

Uploaded by

ankitas5912
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Practical No : 01

Practical Description: Write a program to calculate gcd of two numbers.


Solution:-
# define a function
def compute_hcf(x, y):

# choose the smaller number


if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

num1 = int(input("Enter first number:"))


num2 = int(input("Enter second number:"))

print("The H.C.F. is:", compute_hcf(num1, num2))

Output:-

1
Ankita Soni [0902CS221012]
Practical No : 02
Practical Description: Write a program for square root of a number using newton's method
Solution:-
def squareRoot(n, l) :
x=n
count = 0
while (1) :
count += 1
root = 0.5 * (x + (n / x))
if (abs(root - x) < l) :
break
x = root
return root
if __name__ == "__main__" :

n = int(input(“Enter the number: ”))


l = 0.00001
print("Square root of ", n,"is:",squareRoot(n, l))

Output:-

2
Ankita Soni [0902CS221012]
Practical No : 03
Practical Description: write a program to calculate the exponentiation of a number
Solution:-

a=int(input("Enter the first number:"))


b=int(input("Enter the second number:"))
print(a,"is to power",b,"is:", pow(a,b))

Output:-

3
Ankita Soni [0902CS221012]
Practical No : 04
Practical Description: Write a program to print the maximum element in the list.
Solution:-
li=[]
print("Enter the number of elements:")
n=int(input())
for i in range(n):
print("Enter the ",i+1,"number:")
[Link](int(input()))
print("list is:",li)
max=0
for i in range(n):
if(max<li[i]):
max=li[i]
print("Maximum number in the list is:",max)

Output-

4
Ankita Soni [0902CS221012]
Practical No : 05
Practical Description: write a program to implement linear search on list
Solution:-
l=[]
print("Enter the number of elements:")
n=int(input())
for i in range(0,n):
print("Enter the number:",i+1)
[Link](int(input()))
print(l)
print("Enter search element:")
find=False
x=int(input())
for i in range(0,n):
if (x==l[i]):
print("Element found at ",i+1,"position")
find=True
if(find==False):
print("Element does not exist")

Output:-

5
Ankita Soni [0902CS221012]
Practical No : 06
Practical Description: Write a program to perform binary search
Solution:-
def binary_search(arr, low, high, x):

if high >= low:


mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1

n=int(input("Enter number of elements:"))


x =int(input("Enter element to be searched:"))
arr=[]
for i in range(0,n):
[Link](int(input()))
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

6
Ankita Soni [0902CS221012]
Output:-

7
Ankita Soni [0902CS221012]
Practical No : 07
Practical Description: Write a program to implement selection sort
Solution:-

n=int(input("Enter number of elements:"))

A=[]

for i in range(n):

a=input()

[Link](int(a))

for i in range(len(A)):

min_idx = i

for j in range(i+1, len(A)):

if A[min_idx] > A[j]:

min_idx = j

A[i], A[min_idx] = A[min_idx], A[i]

print ("Sorted array is :",A)

Output:-

8
Ankita Soni [0902CS221012]
Practical No : 08
Practical Description: Write a program to implement insertion sort.
Solution:-
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
n=int(input("Enter number of elements:"))
arr = []
for i in range(n):
a=input()
[Link](int(a))
insertionSort(arr)
print ("Sorted array is:", arr)

Output:-

9
Ankita Soni [0902CS221012]
Practical No : 09
Practical Description: Write a program to implement merge sort
Solution:-

def merge(arr, l, m, r):


n1 = m - l + 1
n2 = r- m

L = [0] * (n1)
R = [0] * (n2)

for i in range(0 , n1):


L[i] = arr[l + i]

for j in range(0 , n2):


R[j] = arr[m + 1 + j]

i=0
j=0
k=l

while i < n1 and j < n2 :


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

10
Ankita Soni [0902CS221012]
while i < n1:
arr[k] = L[i]
i += 1
k += 1

while j < n2:


arr[k] = R[j]
j += 1
k += 1

def mergeSort(arr,l,r):
if l < r:
m = (l+(r-1))//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)

n=int(input("Enter number of elements:"))


arr = []
for i in range(n):
a=input()
[Link](int(a))
n = len(arr)
print ("Given array list is:", arr),

mergeSort(arr,0,n-1)
print ("\n\nSorted array is:",arr)

11
Ankita Soni [0902CS221012]
OUTPUT:-

12
Ankita Soni [0902CS221012]
Practical No : 10
Practical Description: Write a program to find first n prime numbers.
Solution:-
num=int(input("Enter the number:"))
c=2
while num!=0:
for i in range(2,c):
if c%i==0:
break
else:
print(c,end=" ")
num-=1
c+=1
Output:-

13
Ankita Soni [0902CS221012]
Practical No : 11
Practical Description: Write a program to multiply two matrices
Solution:-
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

Output:-

14
Ankita Soni [0902CS221012]
Practical No : 12
Practical Description: write a program for command line arguments.
Solution:-
import sys
n = len([Link])
print("Total arguments passed:", n)
print("\nName of Python script:", [Link][0])

print("\nArguments passed:", end = " ")


for i in range(1, n):
print([Link][i], end = " ")
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int([Link][i])
print("\n\nResult:", Sum)

Output:-

15
Ankita Soni [0902CS221012]
Practical No : 13
Practical Description: write a program to count the most frequent word in a text file
Solution:-
count = 0;
word = "";
maxCount = 0;
words = [];
#Opens a file in read mode
file = open("[Link]", "r")
for line in file:
string = [Link]().replace(',','').replace('.','').split(" ");
for s in string:
[Link](s);
for i in range(0, len(words)):
count = 1;
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;
if(count > maxCount):
maxCount = count;
word = words[i];
print("Most repeated word: " + word);
[Link]();

Output:-

16
Ankita Soni [0902CS221012]
Practical No : 14
Practical Description: write a program to simulate elliptical orbit in pygame
Solution:-
import pygame
import math
import sys
[Link]()
screen = [Link].set_mode((600, 300))
[Link].set_caption("Elliptical orbit")
#creating clock variable
clock=[Link]()
while(True):
for event in [Link]():
if [Link] == [Link]:
[Link]()
xRadius = 250
yRadius = 100
for degree in range(0,360,10):
x1 = int([Link](degree * 2 * [Link]/360) * xRadius)+300
y1 = int([Link](degree * 2 * [Link]/360) * yRadius)+150
[Link]((0, 0, 0))
[Link](screen, (255, 69, 0), [300, 150], 40)
[Link](screen,(255,255,255),[50,50,500,200],1)
[Link](screen, (0, 255, 0), [x1, y1], 20)
[Link]()
[Link](5)# screen refresh rate

17
Ankita Soni [0902CS221012]
Output:-

18
Ankita Soni [0902CS221012]
Practical No : 15
Practical Description: write a program for bouncing ball in pygame
Solution:-
import sys, pygame

[Link]()

size = width, height = 800,400

speed = [1, 1]

background = 255, 255, 255

screen = [Link].set_mode(size)

[Link].set_caption("Bouncing ball")

ball = [Link]("[Link]")

ballrect = ball.get_rect()

while 1:

for event in [Link]():

if [Link] == [Link]:

[Link]()

ballrect = [Link](speed)

19
Ankita Soni [0902CS221012]
if [Link] < 0 or [Link] > width:

speed[0] = -speed[0]

if [Link] < 0 or [Link] > height:

speed[1] = -speed[1]

[Link](background)

[Link](ball, ballrect)

[Link]()

Output:-

20
Ankita Soni [0902CS221012]

You might also like