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

python lab manual UPDATED AUG 27.8.24 (1) (1)

The document outlines a series of Python programming experiments, including algorithms and flowcharts for various tasks such as electricity billing, retail shop billing, and mathematical computations. Each experiment includes an aim, algorithm, program code, and results confirming successful execution. The document serves as a practical guide for implementing basic programming concepts and operations.
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)
5 views

python lab manual UPDATED AUG 27.8.24 (1) (1)

The document outlines a series of Python programming experiments, including algorithms and flowcharts for various tasks such as electricity billing, retail shop billing, and mathematical computations. Each experiment includes an aim, algorithm, program code, and results confirming successful execution. The document serves as a practical guide for implementing basic programming concepts and operations.
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
You are on page 1/ 78

Sl.

Page
Date Name of the Experiment Mark Sign
No. No.

Algorithm, Flowchart, Pseudo code – Microsoft


Office
1.a Electricity Billing

1.b Retail shop billing

1.c Sin series

Python programming - Simple Statements and Expressions

2. Exchange the values of two variables

3. Circulate the values of n variables

4. Calculate distance between two points

5. Compute the GCD of two numbers


Find the square root of a number (Newton’s
6.
method)
7. Exponentiation (power of a number)

8. Check a number is odd or even

9. Calculate the average of numbers in a list

10. Display the grade of a Student

11. Find the sum of digits in a number

12. Find the maximum number in a list

13. Check the number is palindrome or not

14. Print the table of a number

15. Pascal's triangle

16. Sum of first 'n' natural numbers

17. Matrix addition and Subtraction


S.
Date Name of the Experiment Mark Sign
No

18. Count the number of vowels

19. Check Armstrong number

20. Convert Celsius to Fahrenheit

21. Linear search

22. Binary search

23. Selection sort

24. Insertion sort

25. Merge sort

26. First n prime numbers

27. Matrix multiplication

28. Command line arguments (word count)


Find the most frequent words in a text read
29.
from a file
30. Simulate elliptical orbits using Pygame

31. Simulate bouncing ball using Pygame


Ex. No. : 1.a Electricity Billing Date:

Start

Read a value in unit consumed

Amount = unit *0.5


Unit Yes
S_charge = amount *0.20

Amount = 25 + (unit -50)*0.75


Unit Yes S_charge = amount *0.20

Amount = 100(unit-150) *1.25


Unit Yes S_charge = amount *0.20

Amount = 220 + (unit -250) * 1.50

Total_amount = amount + s_charge

Print total amount

Stop

Result:

Thus the flowchart for solving electricity billing problem is designed and it is
verified.
Ex. No. : 1.b Retail Shop Billing Date:

Result:

Thus the flowchart for solving retail shop billing problem is designed and it
is verified.
Ex. No. : 1.c Sine Series Date:

Read Degree

sine(deg)

cosine(deg)

Result:

Thus the flowchart for solving sine series problem is designed and it is
verified.
Output :
Ex. No. : 2 EXCHANGE THE VALUES OF TWO VARIABLES Date:

Aim:
To write a Python program to exchange the values of two variables.

Algorithm:
1. Read the values of two values x and y
2. Use any one method
a. Method 1: Using third variable (Temporary)
b. Method 2: WithoutUsing third variable (Temporary)
c. Method 3: Using comma operator
3. Print the swapped values

Program:
Method 1: Using third variable (Temporary)
x =10
y =50
temp =x
x =y
y =temp
print("Value of x:", x)
print("Value of y:", y)
Method 2: WithoutUsing third variable (Temporary)
x =10
y =50
x =x +y
y =x -y
x =x -y
print("Value of x:", x)
print("Value of y:", y)
Method 3: Using comma operator
x =10
y =50
x, y =y, x
print("Value of x:", x)
print("Value of y:", y)

Result:
Thus the Python program to exchange the values of two variables is executed
successfully and the output is verified.
Output :
Ex. No. : 3 CIRCULATE THE VALUES OF N VARIABLES Date:

Aim:
To write a Python program to circulate the values of n variables.

Algorithm:
1. Read the value of no. of items
2. Initialize a list variable with null value
3. Use for loop to read the items and append the items in list
4. Use for loop and pop() funtion to circulate the items and update the
items in the list
5. Print the list after finishing the circulation

Program:
no_of_terms = int(input("Enter number of values : "))
#Read values
list1 = []
for val in range(0,no_of_terms,1):
ele = int(input("Enter integer : "))
list1.append(ele)
#Circulate and display values
print("Circulating the elements of list ", list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)

Result:
Thus the Python program to circulate the values of n variablesis executed
successfully and the output is verified.
Output :
Ex. No. : 4 CALCULATE DISTANCE BETWEEN TWO POINTS Date:

Aim:
To write a Python program to find the distance between two points.

Algorithm:
1. Read the values of two coordinates (x1,x2) and (y1,y2)

√(𝑥2 − 𝑥1)2 + (𝑦2 −


2. Compute the distance d between these points is given by the formula:

𝑦1)2
3. Print the calculated distance value

Program:
x1=int(input("Enter x1 : "))
x2=int(input("Enter x2 : "))
y1=int(input("Enter y1 :
")) y2=int(input("Enter y2
: "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("Distance between",(x1,x2),"and",(y1,y2),"is: ",result)

Result:
Thus the Python program to find the distance between two points is executed
successfully and the output is verified.
Output :
Ex. No. : 5 COMPUTE THE GCD OF TWO NUMBERS Date:

Aim:
To write a Python program to find GCD of two numbers.

Algorithm:
4. Define a function named computeGCD()
5. Find the smallest among the two inputs x and y
6. Perform the following step till smaller+1
i. Check if ((x % i == 0) and (y % i == 0)), then assign GCD=i
7. Print the value of gcd

Program:
defcomputeGCD(x, y):
if x > y:
smaller = y
else:
smaller = x
fori in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i

returngcd

num1 = 54
num2 = 24
# take input from the user
# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))

print("The GCD. of", num1,"and", num2,"is", computeGCD(num1, num2))

Result:
Thus the Python program to compute GCD of two numbers is executed
successfully and the output is verified.
Output:
FIND THE SQUARE ROOT OF A NUMBER
Ex. No. : 6 Date:
(NEWTON’S METHOD)

Aim:
To write a Python Program to find the square root of a number by Newton’s
Method.

Algorithm:
1. Define a function named newtonSqrt().
2. Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.)
3. Use a while loop with a condition better!=approx to perform the following,
i. Set approx.=better
ii. Better=0.5*(approx.+n/approx.)
4. Print the value of approx

Program:
def newton_sqrt(n, tolerance=1e-10, max_iterations=1000):
"""Calculate the square root of a number using Newton's method."""
if n < 0:
raise ValueError("Cannot compute the square root of a negative number")

# Initial guess
guess = n
iteration = 0

while abs(guess * guess - n) > tolerance and iteration < max_iterations:


guess = (guess + n / guess) / 2
iteration += 1

return guess

# Get user input


number = float(input("Enter a number to find the square root: "))

# Calculate the square root


sqrt_result = newton_sqrt(number)

# Print the result


print(f"The square root of {number} is approximately {sqrt_result}.")

Result:
Thus the Python program for finding the square root of a given number by
Output:

Newton’sMethod is executed successfully and the output is verified.


Aim:
Output: EXPONENTIATION
Ex. No. : 7 Date:
(POWER OF A NUMBER)

Aim:
To write a Python program to find the exponentiation of a number.

Algorithm:
1. Define a function named power()
2. Read the values of base and exp
3. Use ‘if’ to check if exp is equal to 1 or not
i. if exp is equal to 1, then return base
ii. if exp is not equal to 1, then return (base*power(base,exp-1))
4. Print the result

Program:
# Get user input for base and exponent
base = float(input("Enter the base: "))
exponent = float(input("Enter the exponent: "))
# Calculate exponentiation using the ** operator
result = base ** exponent
# Print the result
print(f"{base} raised to the power of {exponent} is {result}.")

Result:
Thus the Python program to find the exponentiation of a number is executed
successfully and the output is verified.
Output:
Ex. No. : 8 CHECK A NUMBER IS ODD OR EVEN Date:

Aim:

To write a Python program to check the given number is ODD or EVEN.

Algorithm:

1. Read the number in num to check ODD or EVEN


2. Use if … else statement to num%2 is equal to 0
a. If it is true print number is EVEN
b. Else print number is ODD

Program:

# Function to check if a number is odd or even


def check_odd_even(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"

# Get user input


num = int(input("Enter a number: "))

# Check and print if the number is odd or even


result = check_odd_even(num)
print(f"The number {num} is {result}.")

Result:
Thus the Python program to check if a number is odd or even is executed
successfully and the output is verified.
Output:
Ex. No. : 9 CALCULATE THE AVERAGE OF NUMBERS IN A LIST Date:

Aim:

To write a Python program to calculate the average of numbers in a list.

Algorithm:

1. User must first enter the number of elements which is stored in the
variable n.
2. The value of I ranges from 0 to the number of elements and is
incremented each time after the body of the loop is executed.
3. Then, the element that the user enters is stored in the variable element.
4. a.append(elem) appends the element to the list.
5. Now the value of i is incremented to 2.
6. The new value entered by the user for the next loop iteration is now
stored in elem which is appended to the list.
7. The loop runs till the value of i reaches n.
8. sum(a) gives the total sum of all the elements in the list and dividing it
by the total number of elements gives the average of elements in the list.
9. round(avg,2) rounds the average upto 2 decimal places.
10. Then the average is printed after rounding.

Program:

# Get the number of elements from the user


num_elements = int(input("Enter the number of elements: "))

# Initialize an empty list


numbers = []

# Collect the numbers from the user


for _ in range(num_elements):
num = float(input("Enter a number: "))
numbers.append(num)

# Calculate the average


if len(numbers) > 0:
total_sum = sum(numbers)
average = total_sum / len(numbers)
print("The average of the numbers is:", average)
else:
print("The list is empty. Cannot calculate average.")
Output:

Result:
Thus the Python program to calculate the average of numbers in a list is
executed successfully and the output is verified.
Output:
Ex. No. : 10 DISPLAY THE GRADE OF A STUDENT Date:

Aim:

To write a Python program to display the grade of a student.

Algorithm:

1. User must enter 5 different values and store it in separate variables.


2. Then sum up all the five marks and divide by 5 to find the average of the
marks.
3. If the average is greater than 90, “Grade: A” is printed.
4. If the average is in between 80 and 90, “Grade: B” is printed.
5. If the average is in between 70 and 80, “Grade: C” is printed.
6. If the average is in between 60 and 70, “Grade: D” is printed.
7. If the average is anything below 60, “Grade: F” is printed.
8. Exit.

Program:

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if avg >= 90:
print("Grade: A")
elif avg >= 80:
print("Grade: B")
elif avg >= 70:
print("Grade: C")
elif avg >= 60:
print("Grade: D")
else:
print("Grade: F")

Result:
Thus the Python program to display the grade of a student is executed
successfully and the output is verified.
Output:

Ex. No. : 11 FIND THE SUM OF DIGITS IN A NUMBER Date:

Aim:

To write a Python program to find the sum of digits in a number.

Algorithm:

1. User must first enter the value and store it in a variable.


2. The while loop is used and the last digit of the number is obtained by
using the modulus operator.
3. The digit is added to another variable each time the loop is executed.
4. This loop terminates when the value of the number is 0.
5. The total sum of the number is then printed.

Program:

def sum_of_digits(number):
# Take the absolute value to handle negative numbers
number = abs(number)
total_sum = 0

# Loop until the number becomes 0


while number > 0:
digit = number % 10 # Extract the last digit
total_sum += digit # Add the digit to the sum
number = number // 10 # Remove the last digit

return total_sum

# Get user input


num = int(input("Enter a number: "))
print("The sum of the digits is:", sum_of_digits(num))
Result:
Thus the Python program to find the sum of digits in a number is executed
successfully and the output is verified.
Output:
Ex. No. : 12 FIND THE MAXIMUM NUMBER IN A LIST Date:

Aim:

To write a Python program to find the maximum number in a list.

Algorithm:

1. User must enter the number of elements and store it in a variable.


2. User must then enter the elements of the list one by one using a for loop
and store it in a list.
3. The list should then be sorted.
4. Then the last element of the list is printed which is also the largest
element of the list.

Program:

a=[1,2,3,4,5]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:", a[n-1])

Result:
Thus the Python program to find maximum number in a list is executed
successfully and the output is verified.
Output:
Ex. No. : 13 CHECK THE NUMBER IS PALINDROME OR NOT Date:

Aim:

To write a Python program to check the number is palindrome or not.

Algorithm:

1. User must first enter the value of the integer and store it in a variable.
2. The value of the integer is then stored in another temporary variable.
3. The while loop is used and the last digit of the number is obtained by
using the modulus operator.
4. The last digit is then stored at the one’s place, second last at the ten’s
place and so on.
5. The last digit is then removed by truly dividing the number with 10.
6. This loop terminates when the value of the number is 0.
7. The reverse of the number is then compared with the integer value stored
in the temporary variable.
8. If both are equal, the number is a palindrome.
9. If both aren’t equal, the number isn’t a palindrome.
10. The final result is then printed.

Program:

def is_palindrome(num):
original = num
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
return original == reversed_num
n = int(input("Enter a number: "))
if is_palindrome(n):
print("The number is a palindrome!")
else:
print("The number is not a palindrome.")

Result:
Thus the Python program to check the number is palindrome or not is
Output:

executed successfully and the output is verified.


Aim:
Output:
Ex. No. : 14 Print the table of a number Date:

To write a Python program to print the table of a number.

Algorithm:

1. User must enter a number.


2. Using a print statement, print the multiplication tables of the given
number.

Program:

n=int(input("Enter the number to print the tables for:"))


for i in range(1,11):
print(n, "x", i, "=", n * i)

Result:
Thus the Python program to print table of a number is executed successfully
and the output is verified.
Aim:
Output:
Ex. No. : 15 PASCAL'S TRIANGLE Date:

To write a Python program to generate pascal's triangle.

Algorithm:

1. User must enter the number of rows that the Pascal’s triangle should
have.
2. The for loop is used to append sub-lists into an empty list defined earlier.
3. Then 1 is appended into all the sub-lists.
4. The for loop is used to determine the value of the number inside the
triangle which is the sum of the two numbers above it.
5. The other for loop is used to print the Pascal’s triangle according to the
format.

Program:

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


a=[]
for i in range(n):
a.append([])
a[i].append([1])
for j in range(1,i):
a[i].append(a[i-1][j-1]+a[i-1][j])
if(n!=0):
a[i].append(1)
for i in range(n):
print(""*(n-i),end="",sep="")
for j in range(0,i+1):
print('{0:6}').format(a[i][j],end="")
print()

Result:
Thus the Python program to generate pascal’s triangle is executed
successfully and the output is verified.
Aim:
Output:

EXP 16: To calculate the sum of first ‘n’ natural numbers


To write a Python program to calculate the sum of first 'n' natural numbers.

Algorithm:

1. User must enter the number of natural numbers to find the sum of.
2. The sum variable is initialized to 0.
3. The while loop is used to find the sum of natural numbers and the
number is decremented for each iteration.
4. The numbers are added to the sum variable and this continues till the
value of the variable is greater than 0.
5. When the value of the variable becomes lesser than 0, the total sum of N
natural numbers is printed.

Program:

n=int (input("Enter a number: "))


sum1 =0
while (n >0):
sum1=sum1+n
n=n-1
print ("The sum of first n natural numbers is",sum1)

Result:
Thus the Python program to calculate sum of n natural numbers is executed
successfully and the output is verified.
EXP 17: To perform matrix addition and subtraction

To write a Python program to perform matrix addition and subtraction.

Algorithm:

1. Start the program.


2. Declare X and Y matrix and initialize the values for manipulation.
3. Declare resultant matrix RA,RS and initialize the values as zero for
storing the manipulated values.
4. Iterate the loops with the variables for row(i) and column(j) to add and
subtract the X and Y matrix.
5. The resultant values will be stored in the respected resultant matrix RA
and RS.
6. Print the resultant matrix RA and RS.
7. Stop the process.
Output:
Program:

X = [[12, 7, 3], [4, 5, 6], [7, 8, 9]]


Y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]]
resultA = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
resultS = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

# Addition
for i in range(len(X)):
for j in range(len(X[0])):
resultA[i][j] = X[i][j] + Y[i][j]

# Subtraction
for i in range(len(X)):
for j in range(len(X[0])):
resultS[i][j] = X[i][j] - Y[i][j]

# Print the results


print("Addition Result:")
for r in resultA:
print(r)

print("\nSubtraction Result:")
for r in resultS:
print(r)

Result:
Thus the Python program for matrix addition and subtraction is executed
successfully and the output is verified.
Output:
Ex. No. : 18 COUNT THE NUMBER OF VOWELS Date:

To write a Python program to count the number of vowels.

Algorithm:

1. User must enter a string and store it in a variable.


2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. An if statement checks if the character is a vowel or not.
5. The count is incremented each time a vowel is encountered.
6. The total count of vowels in the string is printed.

Program:

# Get user input


string = input("Enter string: ") # Use input() instead of raw_input() for Python 3

# Initialize the vowel count


vowels = 0

# Iterate through each character in the string


for i in string:
# Check if the character is a vowel
if i in 'aeiouAEIOU':
vowels += 1

# Print the result


print("Number of vowels are:", vowels)

Result:
Thus the Python program to count the number of vovels is executed
successfully and the output is verified.
Output:
Aim:
Ex. No. : 19 CHECK ARMSTRONG NUMBER Date:

To write a Python program to check the number is Armstrong or not.

Algorithm:

1. Start
2. Read a value in a variable ‘num’
3. Initialize zero to the variable ‘sum’
4. Transfer num value to a temp variable.
5. Check a condition temp > 0, if it is greater than 0
a. digit = temp % 10]
b. sum += digit ** 3
c. temp //= 10
6. Then check a condition num = sum, if it is print as it’s a Armstrong
number
7. Else print as not an Armstrong number
8. Stop the process.

Program:
num = int(input("Enter a number: "))
sum = 0
temp = num

while temp > 0:


digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")

Result:
Thus the Python program to check armstrong number is executed
successfully and the output is verified.
Output
Aim:
Ex. No. : 20 CONVERT CELSIUS TO FAHRENHEIT Date:

To write a Python program to convert the Celsius vale to Fahrenheit.

Algorithm:

1. Start.
2. Read the celsius value in a variable ‘celsius’.
3. Perform an operation fahrenheit=(celsius * 1.8)+ 32
4. Print the Fahrenheit value.
5. Stop the process.

Program:
celsius = float(input("Enter the Celsius value: "))
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' % (celsius,
fahrenheit))

Result:
Thus the Python program to convert celsius to fahrenheitis
executed successfully and the output is verified.
Output:

Aim:
Exp no:21 To perform Linear search

To write a Python Program to perform Linear Search

Algorithm:
1. Read n elements into the list
2. Read the element to be searched
3. If alist[pos]==item, then print the position of the item
4. Else increment the position and repeat step 3 until pos reaches the
length of the list

Program:
def search(alist, item):
pos = 0
found = False
stop = False

while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
print("Element found at position", pos)
else:
if alist[pos] > item:
stop = True
pos += 1

return found

a = []

n = int(input("Enter upper limit: "))


for i in range(0, n):
e = int(input("Enter an element: "))
a.append(e)

x = int(input("Enter element to search: "))


if not search(a, x):
print("Element not found")

Result:
Thus the Python Program to perform linear search is executed successfully
and the output is verified.

Aim:
Output:
Exp22: To perform binary search

To write a Python Program to perform binary search.


Aim:

Algorithm:
1. Read the search element
2. Find the middle element in the sorted list
3. Compare the search element with the middle element
i. if both are matching, print element found
ii. else then check if the search element is smaller or larger than the
middle element
4. If the search element is smaller than the middle element, then repeat
steps 2 and 3 for the
5. left sublist of the middle element
6. If the search element is larger than the middle element, then repeat
steps 2 and 3 for the
7. right sublist of the middle element
8. Repeat the process until the search element if found in the list
9. If element is not found, loop terminates

Program:
def bsearch(alist, item):
first = 0
last = len(alist) - 1
found = False

while first <= last and not found:


mid = (first + last) // 2
if alist[mid] == item:
found = True
print("Element found at position", mid)
else:
if item < alist[mid]:
last = mid - 1
else:
first = mid + 1

return found

a = []
n = int(input("Enter upper limit: "))
for i in range(n):
e = int(input("Enter an element: "))
a.append(e)

a.sort() # Ensure the list is sorted for binary search


x = int(input("Enter element to search: "))
if not bsearch(a, x):
print("Element not found")

Result:
Thus the Python Program to perform binary search is executed successfully
and the output is verified
Output:
Ex. No. : 23 SELECTION SORT Date:
`
Aim:
To write a Python Program to perform selection sort.

Algorithm:
1. Create a function named selectionsort
2. Initialisepos=0
3. If alist[location]>alist[pos] then perform the following till i+1,
4. Set pos=location
5. Swap alist[i] and alist[pos]
6. Print the sorted list

Program:
def selectionSort(alist):
for i in range(len(alist) - 1, 0, -1):
pos = 0
for location in range(1, i + 1):
if alist[location] > alist[pos]:
pos = location
temp = alist[i]
alist[i] = alist[pos]
alist[pos] = temp

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
selectionSort(alist)
print(alist)

Result:
Thus the Python Program to perform selection sort is successfully executed
and the output is verified.
Output:
Ex. No. : 24 INSERTION SORT Date:

Aim:
To write a Python Program to perform insertion sort.

Algorithm:
1. Create a function named insertionsort
2. Initialisecurrentvalue=alist[index] and position=index
3. while position>0 and alist[position-1]>currentvalue, perform the
following till len(alist)
4. alist[position]=alist[position-1]
5. position = position-1
6. alist[position]=currentvalue
7. Print the sorted list

Program:
def insertionSort(alist):
for index in range(1, len(alist)):
currentvalue = alist[index]
position = index

while position > 0 and alist[position - 1] > currentvalue:


alist[position] = alist[position - 1]
position -= 1

alist[position] = currentvalue

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
insertionSort(alist)
print(alist)

Result:
Thus the Python program to perform insertion sort is successfully executed
and the output is verified.
Exp no:25 Merge Sort

To write a Python Program to perform Merge sort.


Aim:

Algorithm:
1. Create a function named mergesort
2. Find the mid of the list
3. Assign lefthalf = alist[:mid] and righthalf = alist[mid:]
4. Initialisei=j=k=0
5. while i<len(lefthalf) and j <len(righthalf), perform the following
iflefthalf[i] <righthalf[j]:
alist[k]=lefthalf[i]
Increment i
else
alist[k]=righthalf[j]
Increment j
Increment k
6. while i<len(lefthalf),perform the following
alist[k]=lefthalf[i]
Increment i
Increment k
7. while j <len(righthalf), perform the following
alist[k]=righthalf[j]
Increment j
Increment k
8. Print the sorted list

Program:
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]

mergeSort(lefthalf)
mergeSort(righthalf)

i=j=k=0

while i < len(lefthalf) and j < len(righthalf):


if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i += 1
else:
alist[k] = righthalf[j]
j += 1
k += 1

while i < len(lefthalf):


alist[k] = lefthalf[i]
i += 1
k += 1

while j < len(righthalf):


alist[k] = righthalf[j]
j += 1
k += 1

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
mergeSort(alist)
print(alist)
Aim:
Result:
Thus the Python program to perform merge sort is successfully executed and
the output is verified.
Output:

Exp no: 26 First n Prime numbers

To write a Python program to find first n prime numbers.

Algorithm:
1. Read the value of n
2. for num in range(0,n + 1), perform the following
3. if num%i is 0 then break
else print the value of num
4. Repeat step 3 for i in range(2,num)

Program:
n = int(input("Enter the upper limit: "))
print("Prime numbers are:")

for num in range(2, n + 1): # Prime numbers are greater than 1


for i in range(2, num):
if (num % i) == 0:
break # Not a prime number
else:
print(num)

Result:
Thus the Python Program to find the first n prime numbers is executed
successfully and the output is verified.
Output:

EXP 27: Multiply matrices

To write a Python program to multiply matrices.

Algorithm:
1. Define two matrices X and Y
2. Create a resultant matrix named ‘result’
3. for i in range(len(X)):
a) for j in range(len(Y[0])):
1. for k in range(len(Y))
2. result[i][j] += X[i][k] * Y[k][j]
4. for r in result, print the value of r

Program:
X = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
Y = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

# Initialize the result matrix with zeros


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

# Perform matrix multiplication


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]

# Print the result matrix


for r in result:
print(r)

Result:
Thus the Python program to multiply matrices is executed successfully and
the output is verified.
Output:
Ex. No. : 28 COMMAND LINE ARGUMENTS(WORD COUNT) Date:

To write a Python program to find word count using command line arguments.

Algorithm:
1. Add arguments to find the words and lines
2. Add the filename as argument
3. Parse the arguments to get the values
4. Format and print the words and lines

Program:
parser=argparse.ArgumentParser()
parser.add_argument('--words','-w',action='store_true')
parser.add_argument('--lines','-l',action='store_true')
parser.add_argument('filename')
args=parser.parse_args()
ifargs.words:
print("words {}".format(print_words(args.filename))
elifargs.lines:
print("lines {}".format(print_lines(args.filename))
else:
print ("words {}".format(print_words(args.filename))
print("lines {}".format(print_lines(args.filename))

Result:
Thus the Python program for command line arguments is executed
successfully and the output is verified.
Aim:
Output: FINDING MOST FREQUENT WORDS IN A TEXT
Ex. No. : 29 Date:
READ FROM A FILE

To write a Python program to find the most frequent words in a text read from
a file.
Algorithm:
1. Read the filename
2. Open the file in read mode
3. Read each line from the file to count the lowers and words
4. Read each line from the file to replace the punctuations
5. Split each line into words and count them
6. Print the words and counts

Program:
def main():
filename=raw_input("enter the file").strip()
infile=open(filename,"r")
wordcounts={}
for line in infile:
processLine(line.lower(),wordcounts)
pairs=list(wordcounts.items())
items=[[x,y] for (y,x) in pairs]
items.sort()
fori in range(len(items)-1,len(items)-11,-1):
print(items[i][1]+"\t"+str(items[i][0]))
defprocessLine(line,wordcounts):
line=replacePunctuations(line)
words=line.split()
for word in words:
if word in wordcounts:
wordcounts[word]+=1
else:
wordcounts[word]=1
defreplacePunctuations(line):
forch in line:
ifch in "~@#$%^&*()_-+=<>?/.,:;!{}[]''":
line=line.replace(ch," ")
return line
main()

Result:
Thus the Python program to find the most frequent words in a text read from
a file is executed successfully and the output is verified.
Aim:
Output:
Ex. No. : 30 SIMULATE ELLIPTICAL ORBITS USING PYGAME Date:

To write a Python program to simulate elliptical orbits in Pygame.


Algorithm:
1. Import the required packages
2. Set up the colours for the elliptical orbits
3. Define the parameters to simulate elliptical orbits
4. Display the created orbits

Program:
import math
import random
importpygame
class Particle ():
def init (self, x, y, colour=0x000000):
self.x = x
self.y = y
self.vx = 0
self.vy = 0
self.colour = colour
defapply_gravity (self, target):
dsqd = (self.x - target.x) ** 2 + (self.y - target.y) ** 2
#g = G*m/dsqd * normalized (self - target)
ifdsqd == 0:
return
self.vx += -1 / dsqd * (self.x - target.x) / dsqd ** 0.5
self.vy += -1 / dsqd * (self.y - target.y) / dsqd ** 0.5
def update (self):
self.x += self.vx
self.y += self.vy
pygame.init()
window = pygame.display.set_mode ((600, 400))
main_surface = pygame.Surface ((600, 400))
colours = [0x000000, 0x111111, 0x222222, 0x333333, 0x444444, 0x555555,
0x666666, 0x777777, 0x888888, 0x999999, 0xaaaaaa, 0xbbbbbb] +
[0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF,
0x888888, 0xFFFFFF, 0x808000, 0x008080, 0x800080, 0x800000]
#colours = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF,
0x00FFFF, 0x888888, 0xFFFFFF, 0x808000, 0x008080, 0x800080,
0x800000]

particles = [Particle (200, 100, colours [i]) for i in range (20)]


earth = Particle (200, 200)
fori, p in enumerate
(particles): p.vx = i /
100
while (True):
# main_surface.fill(0x000000)
Aim: pygame.draw.circle (main_surface, 0x00FF00, (earth.x, earth.y), 5, 2)
for p in particles:
p.apply_gravity (earth)
p.update ()
pygame.draw.circle (main_surface, p.colour, (int (p.x), int (p.y)),
5, 2)
window.blit(main_surface, (0, 0))
pygame.display.flip()

Result:
Thus the Python Program to simulate elliptical orbits using Pygame is
executedsuccessfully and the output is verified.
Output:
Ex. No. : 31 SIMULATE BOUNCING BALL USING PYGAME Date:

Aim:
To write a Python program to simulate bouncing ball in Pygame.

Algorithm:
1. Import the required packages
2. Define the required variables
3. Define the screen space to display the bouncing balls in that space

Program:
import sys
importpygame
pygame.init()

size = width, height = 320, 240


speed = [2, 2]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load('C:\\Users\\admin\\Desktop//ball.jpg')
ballrect = ball.get_rect()

while 1:
for event in pygame.event.get():
ifevent.type == pygame.QUIT: sys.exit()

ballrect = ballrect.move(speed)
ifballrect.left< 0 or ballrect.right> width:
speed[0] = -speed[0]
ifballrect.top< 0 or ballrect.bottom> height:
speed[1] = -speed[1]

screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
Result:
Thus the Python Program to simulate bouncing ball using Pygame is executed
successfully and the output is verified.

You might also like