Professional Documents
Culture Documents
Ge8161 - Problem Solving and Python Programming: Manual
Ge8161 - Problem Solving and Python Programming: Manual
PYTHON PROGRAMMING
Manual
( First semester B.E/B.Tech. Students for the Academic Year 2017-18 )
EX.NO:
DATE: Jeppiaar Engineering College
1. Students are expected to be punctual to the lab classes. If they are late, they will be
considered absent for that particular session.
2. Students must bring their observation note, record note (completed with previous
experiment) to every lab class without fail.
3. Students are advised to come with full preparation for their lab sessions by
Reading the detailed procedure of the exercise from the laboratory manual.
4.Completion of observation note book (i.e.) Aim, Procedure, Algorithm,Program should be written
and Flowchart should be drawn in the observation note before entering into the laboratory.
6. Students are advised to enter their results evaluated in the observation note book on
the same day of that exercise.
7. Assessment marks for each exercise is based only on their performance in the
laboratory.
8. Record note has to be completed then and there and get corrected when the
students are coming for the next lab class.
INDEX
NO DATE
3. Exponentiation CO2
(power of a number)
10. If any of the students is absent for the lab class for genuine reasons, he/she will be
permitted to do the exercise during the repetition class only.
11. If any student is found causing damage to the lab equipments, he/she shall replace
the same with a new.
6. Find the maximum of a list CO4
of numbers
AIM
To find the Greatest Common Divisor (GCD) of two given numbers.
ALGORITHM:
PYTHON CODE:
OUTPUT:
RESULT:
AIM
To find the Square root of a number.
ALGORITHM:
STEP1: The first parameter Iis the value whose square root will be approximated.
STEP2: The second is the number of times to iterate the calculation yielding a
STEP3: Better result from the user.
STEP4: Calculatebetterapprox=0.5*(approx. + n/approx.)
STEP5: Print the final result
STEP6: Exit
PYTHON CODE:
def newtonSqrt(n, howmany):
approx = 0.5 * n
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
return betterapprox
a=float(input('number to Find the Square Root'))
b=int(input('iteration Count'))
print('The Square Root of ',a,' is ',newtonSqrt(a,b))
OUTPUT:
RESULT:
AIM
To find the Exponentiation of a number.
ALGORITHM:
PYTHON CODE:
import math
a=float(input('Enter the number to find exponent'))
e=math.exp(a)
print('e ^',a,' = ',e)
OUTPUT:
RESULT:
LINEAR SEARCH
AIM
To find the existence of an element using linear search
ALGORITHM:
STEP1: Start the program
STEP2: Read list of elements
STEP3: Enter search key element to find its position
STEP4: Read for each item in list
STEP5: If item at position i is search time
STEP6: Print position of element
PYTHON CODE:
OUTPUT:
RESULT:
BINARY SEARCH
AIM
To find the existence of an element using Binary search.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Read list of elements in a and enter search value in variable key
STEP 3: Sort the 'a' values using sort() function and print the sorted list elements.
STEP 4: Perform the binary search operation by calling binarysearch() and store the
return value
STEP 5: If position != -1
Print the element x occurs at position position+1
Else
Print the element is not in the lis
PYTHON CODE:
def binarySearch(arr,low,high,key):
if high>=low:
mid = int ((high+low)/2)
if arr[mid]==key:
return True
if key>arr[mid]:
return binarySearch(arr,mid+1,high,key)
return binarySearch(arr,low,mid-1,key)
return False
if __name__== '__main__':
OUTPUT:
RESULT:
AIM
To find the first N Prime numbers.
ALGORITHM:
PYTHON CODE:
primelist =[]
def getPrime(lower, upper):
for num in range(lower,upper + 1):
if num>1:
for i in range(2,num):
if (num % i) == 0:
break
else:
primelist.append(num)
return primelist
n=int(input("enter n value"))
print (getPrime(0,n))
OUTPUT:
RESULT:
AIM
To find the maximum number in a list.
ALGORITHM:
print('\nEnter the list elements, use space as sperator& terminate by enter key\n')
items = [int(x) for x in input().split()]
mm=max(items)
print('Maximum of the list',items,' is ',mm)
OUTPUT:
RESULT:
SELECTION SORT
AIM
To sort the given list of elements using Selection sort.
ALGORITHM:
PYTHON CODE:
def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
j=0
for k in range(1,i+1):
if alist[k]>alist[j]:
j=k
temp = alist[i]
alist[i] = alist[j]
alist[j] = temp
print('\nEnter the list elements, use space as sperator & terminate by enter key\n')
alist = [int(x) for x in input().split()]
print('Before sorting\n',alist)
selectionSort(alist)
print('After Sorting\n',alist)
OUTPUT:
RESULT:
INSERTION SORT
AIM
To sort the given list of elements using Insertion sort.
ALGORITHM:
k=i
while k>0 and alist[k-1]>j:
alist[k]=alist[k-1]
k = k-1
alist[k]=j
print('\nEnter the list elements, use space as sperator & terminate by enter key\n')
alist = [int(x) for x in input().split()]
print('Before sorting\n',alist)
insertionSort(alist)
print('After Sorting\n',alist)
OUTPUT:
RESULT:
AIM
To remove all duplicate elements from the list.
ALGORITHM:
PYTHON CODE:
print('\nEnter the list elements, use space as sperator& terminate by enter key\n')
x = [int(x) for x in input().split()]
print('Original List - ',x);
x = list(set(x))
print('\nList after Removing the Duplication - ', x)
OUTPUT:
RESULT:
MERGE SORT
AIM
To sort the elements using Merge sort.
ALGORITHM:
STEP1: Start the program
STEP1: Read list of elements
STEP2: Recursively sort the first half of the input
STEP3: Recursively sort the first half of the input
STEP4: Merge two sorted sub-lists into one list
STEP5: Print sorted list
PYTHON CODE:
def mergeSort(alist):
print("Splitting ",alist)
iflen(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
whilei<len(lefthalf) and j <len(righthalf):
iflefthalf[i] <righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
whilei<len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j <len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
print('\nEnter the list elements, use space as sperator& terminate by enter key\n')
alist = [int(x) for x in input().split()]
mergeSort(alist)
OUTPUT:
RESULT:
QUICK SORT
AIM
To sort the elements using Quick sort.
ALGORITHM:
STEP1: Start the program
STEP2: Quicksort works by selecting an element called a pivot
STEP3: Splittingthe array around that pivot such that all the elements in
STEP4: Theleft sub-array are less than pivot and all the elements in the right
sub-array are greater than pivot.
STEP4: The splitting continues until thearray can no longer be broken into pieces.
PYTHON CODE:
# quick sort
def partition(myList, start, end):
pivot = myList[start]
left = start+1
# Start outside the area to be partitioned
right = end
done = False
while not done:
while left <= right and myList[left] <= pivot:
left = left + 1
whilemyList[right] >= pivot and right >=left:
right = right -1
if right < left:
done= True
else:
# swap places
temp=myList[left]
myList[left]=myList[right]
myList[right]=temp
# swap start with myList[right]
temp=myList[start]
myList[start]=myList[right]
myList[right]=temp
return right
OUTPUT:
RESULT:
MATRIX MULTIPLICATION
AIM
To multiply two matrices.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Assign the values for the two matrices and store them in X and Y variables
STEP 3: Initialize the resultant matrix 'result' with '0'
STEP 4: For i=1to length(X)
For j = 1 to length(Y[0])
For K=1 to length(Y)
result[i][j] += x[i][k] * Y[k][j]
STEP 5: Print the result matrix
PYTHON CODE:
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
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]]
fori in range(len(X)):# iterate through rows of X
for j in range(len(Y[0])): # iterate through columns of Y
for k in range(len(Y)): # iterate through rows of Y
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
OUTPUT:
RESULT:
AIM
To count the words in the command line.
ALGORITHM:
PYTHON CODE:
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
OUTPUT:
RESULT:
AIM
To count the frequent words in a text which is read from a file.
ALGORITHM:
PYTHON CODE:
file=open("bar.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
fork,v in wordcount.items():
print (k, v)
OUTPUT:
RESULT: