GE8161 – PROBLEM SOLVING AND
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.
5. Students must get attestations immediately for their output/execution.
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.
JEPPIAAR ENGINEERING COLLEGE
Rajiv Gandhi Salai, Old Mahabalipuram Road, Semmancheri, Chennai, Tamil Nadu 600119
Instructions to the students
2 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
INDEX
EXPERIMENT NAME OF THE EXPERIMENT COMAPPING MARKS SUBMISSION SIGN
DATE
NO DATE
1. Compute the GCD of two CO1
numbers.
2. Find the square root of a CO1
number (Newton’s method)
3. Exponentiation CO2
(power of a number)
4. Linear search and Binary CO3
search
5. First n prime numbers CO3
9. Students must strictly maintain silence during lab classes.
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
7. Selection sort CO4
8. Insertion sort CO4
3 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
9. Merge sort CO4
10. Quick sort CO4
11. Removing all the duplicate CO4
elements in a list
12. Matrix Multiplication CO4
13. Programs that take command CO5
line arguments (word count)
14. Find the most frequent words CO5
in a text read from a file
1.
GCD OF TWO GIVEN NUMBERS
AIM
To find the Greatest Common Divisor (GCD) of two given numbers.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Read the data into the variables x and y
STEP 3: Assign a as x and b as y [for output purpose]
STEP 4: While y != 0
STEP 5: (x,y)=(y, x%y)
STEP 6: Print 'The Greatest Common Divisor of', a,'&',b,' is ', x)
PYTHON CODE:
x=int(input('Enter x -> '))
y=int(input('Enter y -> '))
a=x
b=y
while y != 0:
(x, y) = (y, x % y)
print('Greatest Common Divisor of',a,'&',b,'is',x)
4 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
OUTPUT:
RESULT:
SQUARE ROOT OF A GIVEN NUMBER [NEWTON'S METHOD]
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:
5 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
RESULT:
EXPONENTIATION OF A GIVEN NUMBER
AIM
To find the Exponentiation of a number.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Import math package
STEP 3: Read the number to find exponent value and store it in a. Consider the input in the
form of float, using float function.
STEP 4: Calculate e=math.exp(a)
STEP 6: Print ' e ^ ',a, ' = ', e
PYTHON CODE:
import math
a=float(input('Enter the number to find exponent'))
e=math.exp(a)
print('e ^',a,' = ',e)
OUTPUT:
6 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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:
a = [int(x) for x in input().split()]
print (a)
search = int(input("Enter search number"))
for i in range(0,len(a)):
if (search==a[i]):
print(str(search) + " found at position " +str(i))
if(search!=a[i]):
print(" element not found at any position ")
OUTPUT:
7 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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__':
8 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
a = [int(x) for x in input().split()]
a.sort()
print (a)
key = int(input("Enter the key to be searched\n"))
print (key, "Found in list" if binarySearch(a,0,len(a)-1,key) else "Not found in list")
OUTPUT:
RESULT:
FIRST N PRIME NUMBERS
AIM
To find the first N Prime numbers.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Read the value of 'N' and store it in 'n' variable
STEP 3: Call getprime() by passing 'n' as a parameter of the function to find the first
'term' number of prime numbers. Return the final prime number list
STEP 4: Print the first n prime numbers
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"))
9 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
print (getPrime(0,n))
OUTPUT:
RESULT:
MAXIMUM NUMBER IN A LIST
AIM
To find the maximum number in a list.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Read the list of elements
STEP 3: Apply max() function to find the maximum number from the list
STEP 4: Print the maximum element in the list
PYTHON CODE:
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:
10 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
RESULT:
SELECTION SORT
AIM
To sort the given list of elements using Selection sort.
ALGORITHM:
STEP 1: Start the Program
STEP 2 Read the list of elements and store them in alist
STEP 3 Call selectionSort() function with alist as parameter
STEP 4 Print the sorted list elements
selectionSort()
STEP 5 for i = length(alist)-1 to 0 step -1
STEP 6 Assign j=0
STEP 7 For k = 1 to i+1
If alist[k] >alist[j]
J=k
STEP 8 Assign temp = alist[i]
STEP 9 Assign alist[i] = alist[j]
STEP10 Assign alist[j] = temp
PYTHON CODE:
def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
j=0
11 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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:
STEP 1: Start the Program
STEP 2: Read the list of elements and store them in alist
STEP 3: Call insertionSort() function with alist as parameter
STEP 4: Print the sorted list elements
insertionSort()
STEP 5: for i = 1 to length(alist)
STEP 6: Assign j=alist[i]
STEP 7: Assign k = i
While k > 0 and alist[k-1] > j
STEP 8: Assign alist[k] = alist[k-1]
STEP 9: Assign k = k-1
STEP 10: Assign alist[k] = j
PYTHON CODE:
def insertionSort(alist):
for i in range(1,len(alist)):
j = alist[i]
12 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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:
REMOVING THE DUPLICATE ELEMENTS FROM THE LIST
AIM
To remove all duplicate elements from the list.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Read the list of elements and store them in x
STEP 3: Print the original list
STEP 4: Apply set() function on the list x and finally, make the output as a list and store
it in x
STEP 5: Print the output list without duplication of elements
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:
13 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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
14 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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:
15 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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
16 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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
def quicksort(myList, start, end):
if start < end:
# partition the list
split = partition(myList, start, end)
# sort both halves
quicksort(myList, start, split-1)
quicksort(myList, split+1, end)
returnmyList
myList=[int(x) for x in input().split()]
sortedList = quicksort(myList,0,len(myList)-1)
print(sortedList)
17 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
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],
18 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
[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:
WORDS COUNTING USING COMMAND LINE ARGUMENTS
AIM
To count the words in the command line.
ALGORITHM:
STEP 1: Start the Program
STEP 2: Import sys
STEP 3: Print length of arguments and arguments list
STEP 4: stop
PYTHON CODE:
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
19 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
OUTPUT:
RESULT:
FREQUENT WORD COUNT IN A TEXT READ FROM A FILE
AIM
To count the frequent words in a text which is read from a file.
ALGORITHM:
STEP1: Start the Program
STEP2: Create the input text file named 'bar.txt'
STEP3: Open the created input file and assign it to 'file'
STEP4: initially make wordcount is empty
STEP5: if word not in wordcount,wordcount=1
STEP6: if word in wordcount,wordcount+=1
STEP7: printwordcount
PYTHON CODE:
file=open("bar.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
20 Problem Solving and Python Programming
EX.NO:
DATE: Jeppiaar Engineering College
wordcount[word] += 1
fork,v in wordcount.items():
print (k, v)
OUTPUT:
RESULT:
21 Problem Solving and Python Programming