Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
75 views

Python Programming Jagesh Soni

This document contains a Python programming lab file submitted by Jagesh Soni, a second year CSE student. It includes 14 Python programs covering topics like command line arguments, matrix multiplication, GCD calculation, word frequency, square root calculation, exponentiation, maximum of a list, linear search, binary search, selection sort, insertion sort, merge sort, prime numbers, and simulating a bouncing ball in Pygame.

Uploaded by

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

Python Programming Jagesh Soni

This document contains a Python programming lab file submitted by Jagesh Soni, a second year CSE student. It includes 14 Python programs covering topics like command line arguments, matrix multiplication, GCD calculation, word frequency, square root calculation, exponentiation, maximum of a list, linear search, binary search, selection sort, insertion sort, merge sort, prime numbers, and simulating a bouncing ball in Pygame.

Uploaded by

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

PYTHON PROGRAMMING LAB FILE

SUBMITTED BY:
JAGESH SONI
CSE 2ND YEAR
1805210023

SUBMITTED TO:
MS. PRATHIBHA PANDEY

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

INSTITUTE OF ENGINEERING AND TECHNOLOGY,


LUCKNOW
1.) Python program to take command line arguments as inputs
and to print the number of arguments

import sys

# sys.argv contains all the command line


# arguments passed to a program

# sys.argv[0] contains name of script


# sys.argv[1:] contains all the arguments passed

print(“No. Of arguments passed: “, len(sys.argv[1:])

2.) Python program to do matrix multiplication

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

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

3.) Python program to compute the GCD of two numbers

def hcf(a,b):
if(b==0):
return a
else:
return hcf(b,a%b)

a = 60
b= 48

print ("The gcd of 60 and 48 is : ",end="")


print (hcf(60,48))
4.) Python program to find most frequent word in a text file

fname=input("enter file name")


count=0
maxcount=0
l=[]

with open(fname,'r') as f:
contents=f.read()
words=content.split()

for i in range(len(words)):
for j in range(len(words)):
if(words[i]==words[j]):
count+=1
else:
count=count
if(count==maxcount):
l.append(words[i])
elif(count>maxcount):t
l.clear()
l.append(words[i])
maxcount=count
else:
l=l
count=0

print(l)
5.) Python program to find the square root of a number(Newton’s
method)

def squareRoot(n, l) :

# Assuming the sqrt of n as n only


x = n;

# To count the number of iterations


count = 0;

while (1) :
count += 1;

# Calculate more closed x


root = 0.5 * (x + (n / x));

# Check for closeness


if (abs(root - x) < l) :
break;

# Update root
x = root;

return root;

if __name__ == "__main__" :

n = 327;
l = 0.00001;
print(squareRoot(n, l));
6.) Python program for exponentiation(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))

7.) Python program to find the maximum of a list of numbers

# creating empty list


list = [ ]

# 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: "))
list.append(ele)

# print maximum element


print("Largest element is:", max(list))
8.)Python program to perform linear search

def linearsearch(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1

arr = ['p','y','t','h','o','n']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))

9.)Python program to perform binary search

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

if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
10.)Python program to perform 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]),
11.) Python program to perform 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])
12.) Python program to perform merge sort

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]
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)
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]),

13.) Python program to find first n prime numbers

# Function to print first N prime numbers


def print_first_N_primes(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


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

# Driver code
N = 100;
print_first_N_primes(N);
14.) Python program to simulate bouncing ball in pygame

import sys, pygame


pygame.init()

size = width, height = 700, 300


speed = [1, 1]
background = 255, 255, 255

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")

ball = pygame.image.load("ball.jpg")
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()

You might also like