You are on page 1of 22

Program 1

To write a python program that takes in command line arguments as input


and print the number of arguments.
import sys
print("This is the name of the script:", sys.argv[0])
print("Number of arguments:", len(sys.argv))
print("The arguments are:" , str(sys.argv))

Output:
Program 2
To write a python program to perform Matrix Multiplication.

A=[]
n=int(input("Enter N for N x N matrix: "))
print("Enter the element ::>")
for i in range(n):
row=[]
for j in range(n):
row.append(int(input()))
A. append(row)
print(A)

print("Display Array In Matrix Form")


for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print()

B=[]
n=int(input("Enter N for N x N matrix : "))
print("Enter the element ::>")
for i in range (n):
row=[]
for j in range(n):
row.append(int(input()))
B. append(row)
print(B)

print("Display Array In Matrix Form")


for i in range(n):
for j in range(n):
print(B[i][j], end=" ")
print()

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

for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print("The Resultant Matrix Is ::>")
for r in result:
print(r)
Output:
Program 3
To write a 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,b=map(int,input("Enter two numbers:").split())


print("Gcd of",a,"and",b,"is:",hcf(a,b))

Output:
Program 4
To write a python program to find the most frequent words in a text file.

import string
text = open("fruits.txt", "r")
d = dict()
for line in text:
line = line.strip()
line = line.lower()
line = line.translate(line.maketrans("", "", string.punctuation))
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
for key in list(d.keys()):
print(key, ":", d[key])

Output:
Program 5
To write a python program find the square root of a number (Newton’s
method).

def newton_method(number, number_iters = 100):


a = float(number)
for i in range(number_iters):
number = 0.5 * (number + a / number)
return number

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


b=int(input("Enter second number:"))
print("Square root of first number:",newton_method(a))
print("Square root of second number:",newton_method(b))

Output:
Program 6
To write a python program exponentiation (power of a number).

def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Output:
Program 7
To write a python program find the maximum of a list of numbers.

a=[]
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])

Output:
Program 8
To write a python program linear search.

def linearSearch(array, n, x):

# Going through array sequencially


for i in range(0, n):
if (array[i] == x):
return i
return -1

array = [2, 4, 0, 1, 9]
x=1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)

Output:
Program 9
To write a python program Binary search.

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")
Output:
Program 10
To write a python program selection sort.

def selectionSort(array, size):


for step in range(size):
min_idx = step
for i in range(step + 1, size):

# to sort in descending order, change > to < in this line


# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i

# put min at the correct position


(array[step], array[min_idx]) = (array[min_idx], array[step])

data = [14,46,43,27,57,41,45,21,70]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

Output:
Program 11
To write a python program Insertion sort.

def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)

Output:
Program 12
To write a python program merge sort.

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
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-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
print("%d" % arr[i],end=" ")
mergeSort(arr, 0, n-1) print("\n\
nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")
Output:
Program 13
To write a python program first n prime numbers.

numr=int(input("Enter range:"))
print("Prime numbers:",end=' ')
for n in range(1,numr):
for i in range(2,n):
if(n%i==0):
break
else:
print(n,end=' ')

Output:
Program 14
To write a python program simulate bouncing ball in Pygame.

import pygame
import time
pygame.init() #Initializes pygame
screen=pygame.display.set_mode((500,300)) #Sets the Pygame Window 500*300
y=1 #y co-ordinate of the centre of the ball
direction=1 #To decide whether to Increment/Decrement y value
counter=0 #To count the number of bounces
while True:
screen.fill((255,255,255))#White Screen
pygame.draw.circle(screen,(255,0,0),(250,y),13,0)#Draws the red ball at
(250,y) pygame.display.update()#Updates the above in the Pygame window
time.sleep(.006)#To pause for .006 seconds
if y==300: #The ball is at the bottom of window
direction=-1 #Move up by decrementing by 1
elif y==0: #The ball is at the top of the window
direction=1 #Move down by incrementing by 1
counter=counter+1 #One bounce completed
y=y+direction # Updates the next y co-ordinate of centre of ball
if counter==3: #Three bounces are over
pygame.quit() #Uninitializes pygame and window closes
break #Control comes out of while loop
Output:
Program 15
Write a program to compute area and circumference of a triangle.
Take input from user.

def Area_of_Triangle(a, b, c):


#calculate the Perimeter
Perimeter = a + b + c
#calculate the semi-perimeter
s = (a + b + c) / 2

#calculate the area


Area = (s*(s-a)*(s-b)*(s-c))**(0.5)

print("\n The Perimeter of Traiangle =",Perimeter)


print(" The Semi Perimeter of Traiangle =",s)
print(" The Area of a Triangle is =",round(Area,2))

s1,s2,s3=map(int,input("Enter Three sides of


Triangle:").split()) Area_of_Triangle(s1,s2,s3)

Output:
Program 16
Write a program to check if a number is Odd or even. Take input from
user.

# Python program to check if the input number is odd or


even. # A number is even if division by 2 give a remainder of
0.
# If remainder is 1, it is odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is
Even".format(num)) else:
print("{0} is Odd".format(num))

Output:
Program 17
Write a program to check that a given year is Leap Year or not.

# To get year (integer input) from the user


year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap
year".format(year)) else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

Output:
Program 18
To print ‘n terms of Fibonacci series using iteration.

# Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result nterms = 10
# uncomment to take input from the user
nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive
integer") elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output:

You might also like