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

Python_Lab Manual for University Student

The document outlines a Python programming lab (BTCS409P) consisting of 14 experiments, each with specific aims, source code, and submission dates. Each experiment covers fundamental programming concepts such as command line arguments, matrix multiplication, GCD computation, and various sorting and searching algorithms. The document provides example source codes and expected outputs for each experiment.

Uploaded by

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

Python_Lab Manual for University Student

The document outlines a Python programming lab (BTCS409P) consisting of 14 experiments, each with specific aims, source code, and submission dates. Each experiment covers fundamental programming concepts such as command line arguments, matrix multiplication, GCD computation, and various sorting and searching algorithms. The document provides example source codes and expected outputs for each experiment.

Uploaded by

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

Python Language Programming Lab (BTCS409P)

Index
Experiment Aim Experiment Submission Signature
No. Date Date
1 Write a python program that takes 24/01/24 31/01/24
in command line arguments as
input and print the number of
arguments.
2 Write a python program to 24/01/24 31/01/24
perform Matrix Multiplication.
3 Write a python program to 31/01/24 14/02/24
compute the GCD of two numbers.
4 Write a python program to find the 31/01/24 14/02/24
most frequent words in a text file.
5 Write a python program to find the 14/02/24 21/02/24
square root of a number (Newton’s
method).
6 Write a python program for 14/02/24 21/02/24
exponentiation (power of a
number).
7 Write a python program to find the 21/02/24 28/02/24
maximum of a list of numbers.
8 Write a python program to 21/02/24 28/02/24
implement the linear search.
9 Write a python program to 28/02/24 20/03/24
implement the binary search.

10 Write a python program to 28/02/24 20/03/24


implement the selection sort.
11 Write a python program to 20/03/24 20/03/24
implement the insertion sort.
12 Write a python program to 20/03/24 03/04/24
implement the merge sort.
13 Write a python program to find 03/04/24 10/04/24
first n prime numbers.
14 Write a python program to 03/04/24 10/04/24
simulate the bouncing ball in
Pygame.
Experiment Number 1

Aim: Write a python program that takes in command line arguments as input and print the
number of arguments.
Source Code:
import sys

# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", sys.argv[0])

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


for i in range(1, n):
print(sys.argv[i], end = " ")

# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])

print("\n\nResult:", Sum)

Input/Output:
Total arguments passed 3
Name of Python script: exp1.py
Arguments passed: 1 2 3
Result:6

Page 2 of 19
Experiment No 2
Aim: Write a python program to perform Matrix Multiplication.

Source Code:
# take a 3x3 matrix
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]

# take a 3x4 matrix


B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

result = [[0, 0, 0, 0],


[0, 0, 0, 0],
[0, 0, 0, 0]]

# 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)

Output:

114 160 60 39
74 97 73 18
119 157 112 30

Page 3 of 19
Experiment No 3
Aim: Write a python program to compute the GCD of two numbers.

Source Code:
# Python Program to find GCD of Two Numbers using While loop
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
i=1
while(i <= num1 and i <= num2):
if(num1 % i == 0 and num2 % i == 0):
gcd = i
i=i+1
print("GCD is", gcd)
Input/Output:
Enter 1st number: 24
Enter 2nd number: 72
GCD is 24

Page 4 of 19
Experiment No 4
Aim: Write a python program to find the most frequent words in a text file.

Source Code:
#To read the entire contents of text into a single string
with open('file1.txt', 'r') as f:
contents = f.read()
#to read each line and store them as list
with open('file1.txt', 'r') as f:
lines = f.readlines()
#for iterative method of reading text in files
with open('planets.txt', 'r') as f:
for line in f:
print(len(line))
for i in range(len(words)):
for j in range(len(words)):
if(words[i]==words[j]): #finding count of each word
count+=1
else:
count=count
if(count==maxcount): #comparing with maximum count
l.append(words[i])
elif(count>maxcount): #if count greater than maxcount
l.clear()
l.append(words[i])
maxcount=count
else:
l=l
count=0
print(l)
Input/Output:
Text File: file1.txt
ABCADEFAGHJAKWRTA
Frequent Word A

Page 5 of 19
Experiment No 5
Aim: Write a python program to find the square root of a number (Newton’s method).
Source Code:

# Python Program to calculate the square root

# To take the input from the user


#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

# Find square root of real or complex numbers


# importing the complex math module
import cmath

num = 1+2j

# To take input from the user


#num = eval(input('Enter a number: '))

num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num
,num_sqrt.real,num_sqrt.imag))

Input/Output:

Enter a number: 25
The square root of 5.0

Page 6 of 19
Experiment No 6
Aim: Write a python program for exponentiation (power of a number).
Source Code:

# Python Program to find Power of a Number

number = int(input(" Please Enter any Positive Integer : "))


exponent = int(input(" Please Enter Exponent Value : "))
power = 1

for i in range(1, exponent + 1):


power = power * number

print("The Result of {0} Power {1} = {2}".format(number, exponent, power)

Input/Output:

Please Enter any Positive Integer: 2


Please Enter Exponent Value: 5
The Result of 2 Power 5 = 32

Page 7 of 19
Experiment No 7
Aim: Write a python program to find the maximum of a list of numbers.

Source Code:
# Python program to find largest
# number in a list

# creating empty list


list1 = []

# asking number of elements to put in list


num = int(input("Enter number of elements in list: "))

# iterating till num to append elements in list


for i in range(1, num + 1):
ele = int(input("Enter elements: "))
list1.append(ele)

# print maximum element


print("Largest element is:", max(list1))

Input/Output:
Enter number of elements in list: 7
Enter elements: 3 5 7 10 24 6 9
Largest element is: 24

Page 8 of 19
Experiment No 8
Aim: Write a python program to implement the linear search.

Source Code:
 Start from the leftmost element of given arr[] and one by one compare element x with each
element of arr[]
 If x matches with any of the element, return the index value.
 If x doesn’t match with any of elements in arr[] , return -1 or element not found

def linearsearch(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("Element found at index "+str(linearsearch(arr,x)))

Input/Output:
Element found at index 6

Page 9 of 19
Experiment No 9
Aim: Write a python program to implement the binary search.
Source Code:
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):

# Check base case


if high >= low:

mid = (high + low) // 2

# If element is present at the middle itself


if arr[mid] == x:
return mid

# If element is smaller than mid, then it can only


# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)

# Else the element can only be present in right subarray


else:
return binary_search(arr, mid + 1, high, x)

else:
# Element is not present in the array
return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binary_search(arr, 0, len(arr)-1, x)

Page 10 of 19
if result != -1:
print ("Element is present at index", str(result))
else:
print ("Element is not present in array")

Input/Output:
Element is present at index 4

Page 11 of 19
Experiment No 10
Aim: Write a python program to implement the selection sort.
Source Code:

# Python program for implementation of Selection


# Sort
import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),

Input/Output:

Sorted array 11 12 22 25 64

Page 12 of 19
Experiment No 11
Aim: Write a python program to implement the insertion sort.

Source Code:
# Python program for implementation of Insertion Sort

# Function to do insertion sort


def insertionSort(arr):

# Traverse through 1 to len(arr)


for i in range(1, len(arr)):

key = arr[i]

# Move elements of arr[0..i-1], that are


# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver code to test above


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

Input/Output:
Sorted array is: 5 6 11 12 13

Page 13 of 19
Experiment No 12
Aim: Write a python program to implement the merge sort.
Source Code:

# Python program for implementation of MergeSort

# Merges two subarrays of arr[].


# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m

# create temp arrays


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

# Copy data to temp arrays L[] and R[]


for i in range(0 , n1):
L[i] = arr[l + i]

for j in range(0 , n2):


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

# Merge the temp arrays back into arr[l..r]


i=0 # Initial index of first subarray
j=0 # Initial index of second subarray
k=l # Initial index of merged subarray

while i < n1 and j < n2 :


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

Page 14 of 19
j += 1
k += 1

# Copy the remaining elements of L[], if there


# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1

# Copy the remaining elements of R[], if there


# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1

# l is for left index and r is right index of the


# sub-array of arr to be sorted
def mergeSort(arr,l,r):
if l < r:

# Same as (l+r)//2, but avoids overflow for


# large l and h
m = (l+(r-1))//2

# Sort first and second halves


mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)

# Driver code to test above


arr = [12, 11, 13, 5, 6, 7]
n = len(arr)

Page 15 of 19
print ("Given array is")
for i in range(n):
print ("%d" %arr[i]),

mergeSort(arr,0,n-1)
print ("\n\nSorted array is")
for i in range(n):
print ("%d" %arr[i]),

Input/Output:

Sorted array is 5 6 7 11 12 13

Page 16 of 19
Experiment No 13
Aim: Write a python program to find first n prime numbers.
Source Code:

# Python3 program to display first N Prime numbers

# Function to print first N prime numbers


def print_primes_till_N(N):

# Declare the variables


i, j, flag = 0, 0, 0;

# Print display message


print("Prime numbers between 1 and ",
N , " are:");

# Traverse each number from 1 to N


# with the help of for loop
for i in range(1, N + 1, 1):

# Skip 0 and 1 as they are


# niether prime nor composite
if (i == 1 or i == 0):
continue;

# flag variable to tell


# if i is prime or not
flag = 1;

for j in range(2, ((i // 2) + 1), 1):


if (i % j == 0):
flag = 0;
break;

# flag = 1 means i is prime

Page 17 of 19
# and flag = 0 means i is not prime
if (flag == 1):
print(i, end = " ");

# Driver code
N = 100;
print_primes_till_N(N);

Input/Output:

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
199

Page 18 of 19
Experiment No 14
Aim: Write a python program to simulate the bouncing ball in Pygame.
Source Code:
import sys, pygame
pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()

Input/Output:

Page 19 of 19

You might also like