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

GE8161 Python

The document contains details of 8 experiments on various Python programming concepts: 1. The first experiment involves writing a program to find the greatest common divisor (GCD) of two numbers. 2. The second experiment aims to write a program to find the square root of a number using Newton's method. 3. Finding the exponentiation or power of a number is the goal of the third experiment. 4. Experiment four develops a program to perform linear search on an array. 5. Binary search is implemented in the fifth experiment. 6. Determining the first n prime numbers is the objective of experiment six. 7. Experiment seven finds the maximum number in a list of
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

GE8161 Python

The document contains details of 8 experiments on various Python programming concepts: 1. The first experiment involves writing a program to find the greatest common divisor (GCD) of two numbers. 2. The second experiment aims to write a program to find the square root of a number using Newton's method. 3. Finding the exponentiation or power of a number is the goal of the third experiment. 4. Experiment four develops a program to perform linear search on an array. 5. Binary search is implemented in the fifth experiment. 6. Determining the first n prime numbers is the objective of experiment six. 7. Experiment seven finds the maximum number in a list of
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

INDE

X
Page Marks
Ex.N Date Name of the Experiment Remark
No. Awarded
o. s

Date Name ofEx.No.


the Experiment
I DEX
N Page
No.
Marks
Awarded
Remark
s
1

GCD OF TWO NUMBERS

Exp No: 1

Date :

Aim:

Write a Python program to compute the GCD of two numbers.

Algorithm:

1. Take two numbers from the user as inputs

2. Calculate the remainder d1 % d2

3. While the remainder is not equal to 0

4. D1=D2

5. D2=remainder

6. Remainder=d1 % d2

7. Print the GCD

8. Exit
2

Coding:

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

d2 = int(input("Enter another number"))

rem = d1 % d2

while rem != 0 :

d1 = d2

d2 = rem

rem=d1 % d2

print ("gcd of given numbers is :", d2)


3

Output:

Enter first number : 12

Enter second number : 18

GCD of 12 and 18 is 6.

Result:

Thus the above experiment is successfully compiled and

output is verified.
4

SQUARE ROOT OF A NUMBER

Exp No: 2

Date:

Aim:

Write a Python program to find the square root of a number


(Newton’s method).

Algorithm:

1. The first parameter is the value whose square root will

be approximated

2. The second is the number of times to iterate the

calculation yielding a better result from the user.

3. Calculate better = 1 / 2 * (approx + n / approx )

4. Print the final result

5. Exit
5

Coding:

while True:

print(“Enter ‘x’ for exit. “)

num = input("Enter a number: ")

if num == 'x':

break

else:

number = float(num)

number_sqrt = number ** 0.5

print("Square Root of %0.2f is %0.2f" %(number,

number_sqrt)
6

Output:

Enter a number : 8

Square Root of 8.00 is 2.83

Enter ‘x’ for exit.

Enter a number : 25

Square Root of 25.00 is 5.00

Result:

Thus the above experiment is successfully compiled and

Output is verified.
7

EXPONENTIATION (POWER OF A NUMBER)

Exp No: 3

Date:

Aim:

Write a Python program to find the exponentiation (Power


of number).

Algorithm:

1. Take the base and exponential value from the user

2. Pass the numbers as arguments to a recursive function

to find the power of the number

3. Give the base conditions that if the exponential power

is equal to 1, return the base number.

4. If the exponential power isn’t equal to 1, return the

base number multiplied with the power function called

recursively with the arguments as the base and power

minus 1

5. Print the final result

6. Exit
8

Coding:

n = input ("Enter a number : ")

n = int(n)

e = input ("Enter an exponent : ")

e = int(e)

r = n

for i in range (1,e):

r = n * r

print(r)
9

Output:

Enter a number : 2

Enter an exponent : 2

Result:

Thus the above experiment is successfully compiled and

Output is verified.
10

LINEAR SEARCH

Exp No: 4

Date:

Aim:

Write a Python program to find an element in an array


using Linear Search Technique.

Algorithm:

Linear Search (Array A, Value x)

1. Set i to 1

2. If i > n then goto Step 7

3. If A[i] = X then goto Step 6

4. Set i to i + 1

5. Goto Step 2

6. Print element x found at index i and goto step 8

7. Print element not found

8. Exit.
11

Coding:

list = [4,1,2,5,3]

search = int(input("Enter search number"))

for i in range(0,len(list)):

if search==list[i]:

print(str(search)+"found at position " + str(i))


12

Output:

Enter search number : 5

5 found at position 3

Result:

Thus the above experiment is successfully compiled and

Output is verified.
13

BINARY SEARCH

Exp No: 5

Date:

Aim:

Write a Python program to find an element in an array


using Binary Search Technique.

Algorithm:

Found = False

While not Found and First < = Top

Midpoint = (First + Last) / 2

If List[Midpoint]= ItemSought then

Found= True

Elif First>=Last then

SearchFailed = True

Elif List[Midpoint] > ItemSought Then

Last = MidPoint -1

Else

First = MidPoint + 1

EndIf
14

Coding:

def binary_search(item_list,item):

first = 0

last = len(item_list)-1

found = False

while( first<=last and not found):

mid = (first + last)//2

if item_list[mid] == item :

found = True

else:

if item < item_list[mid]:

last = mid - 1

else:

first = mid + 1

return found

print(binary_search([1,2,3,5,8], 6))

print(binary_search([1,2,3,5,8], 5))
15

Output:

False

True

Result:

Thus the above experiment is successfully compiled and

Output is verified.
16

PRIME NUMBERS

Exp No: 6

Date:

Aim:

Write a Python program to find the first n prime numbers.

Algorithm:

1. Define a function to check the prime number

2. Receive the argument to check prime or not

3. Using if condition check the argument if it is greater


than two if it’s true

4. Define for loop to check the number is prime or not

5. If it is a prime number return true or else false

6. Get the limit to print prime number

7. From lower limit to received limit pass the number to


function.

8. If it is a prime number print it and count the number


of prime numbers

9. Print the final result.

10. Exit
17

Coding:

prime_numbers = 0

def is_prime_number(x):

if x >= 2:

for y in range(2,x):

if not (x % y):

return False

else:

return False

return True

for i in range(int(input("How many numbers you wish to


check:"))):

if is_prime_number(i):

prime_numbers+=1

print(i)

print("We found "+str(prime_numbers)+" prime numbers.")


18

Output:

How many numbers you wish to check : 30

11

13

17

19

23

29

We found 10 prime numbers

Result:

Thus the above experiment is successfully compiled and

Output is verified.
19

MAXIMUM OF N NUMBERS

Exp No: 7

Date:

Aim:

Write a Python program to find the maximum of a list of


numbers.

Algorithm:

1. Take in the number of elements and store it in a


variable

2. Take in the elements of the list one by one

3. Sort the list in ascending order

4. Print the last element of the list

5. Exit
20

Coding:

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


21

Output:

Enter number of elements: 5

Enter element: 11

Enter element: 31

Enter element: 21

Enter element: 51

Enter element: 81

Largest element is : 81

Result:

Thus the above experiment is successfully compiled and

Output is verified.
22

INSERTION SORT

Exp No: 8

Date:

Aim:

Write a Python program to sort an array using insertion


sort method.

Algorithm:

1. If it is the first element, it is already sorted.


Return 1.

2. Pick next element

3. Compare with all elements in sorted sub-list

4. Shift all the elements in the sorted sub-list that is


greater than the value to be sorted.

5. Insert the value

6. Repeat until list if sorted.


23

Coding:

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 = position - 1

alist[position] = currentvalue

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]

insertionSort(alist)

print(alist)
24

Output:

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Result:

Thus the above experiment is successfully compiled and

Output is verified.
25

SELECTION SORT

Exp No: 9

Date:

Aim:

Write a Python program to sort an array using selection


sort method.

Algorithm:

1. Set MIN to location 0

2. Search the minimum element in the list

3. Swap with value at location MIN

4. Increment MIN to point to next element

5. Repeat until list is sorted


26

Coding:

def selectionSort(alist):

for fillslot in range(len(alist) - 1, 0, -1):

positionOfMax = 0

for location in range(1, fillslot + 1):

if alist[location] > alist[positionOfMax]:

positionOfMax = location

temp = alist[fillslot]

alist[fillslot] = alist[positionOfMax]

alist[positionOfMax] = temp

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]

selectionSort(alist)

print(alist)
27

Output:

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Result:

Thus the above experiment is successfully compiled and

Output is verified.
28

REMOVING DUPLICATE ELEMENTS IN THE LIST

Exp No: 10

Date:

Aim:

Write a Python program to remove all the duplicate


elements in the list.

Algorithm:

1. Take the number of elements in the list and store it in


a variable

2. Accept the values into the list using a for loop and
insert them into the list.

3. Use a for loop to traverse through the elements in the


list

4. Use an if statement to check if the element is already


there in the list and if it is not there, append it to
another list

5. Print the non-duplicate items of the list.

6. Exit.
29

Coding:

a=[]

n= int(input("Enter the number of elements in list:"))

for x in range(0,n):

element=int(input("Enter element" + str(x+1) + ":"))

a.append(element)

b = set()

unique = []

for x in a:

if x not in b:

unique.append(x)

b.add(x)

print("Non-duplicate items:")

print(unique)
30

Output:

Enter the number of elements in list: 10

Enter element 1 : 10

Enter element 2 : 20

Enter element 3 : 30

Enter element 4 : 40

Enter element 5 : 50

Enter element 6 : 60

Enter element 7 : 70

Enter element 8 : 80

Enter element 9 : 10

Enter element 10 : 90

Non-duplicate items:

[10, 20, 30, 40, 50, 60, 70, 80, 90]

Result:

Thus the above experiment is successfully compiled and

Output is verified.
31

QUICK SORT

Exp No: 11

Date:

Aim:

Write a Python program to sort an array using Quick sort

method.

Algorithm:

1. Choose the highest index value as pivot.

2. Take two variables to point left and right of the


list excluding pivot

3. Left points to the low index

4. Right points to the high

5. While value at left is less than pivot move right

6. While value at right is greater than pivot move left

7. If both step 5 and step 6 does not match swap left


and right

8. If left >= right, the point where they met is new


pivot.
32

Coding:

def quickSort(alist):

quickSortHelper(alist,0,len(alist)-1)

def quickSortHelper(alist,first,last):

if first<last:

splitpoint = partition(alist,first,last)

quickSortHelper(alist,first,splitpoint-1)

quickSortHelper(alist,splitpoint+1,last)

def partition(alist,first,last):

pivotvalue = alist[first]

leftmark = first+1

rightmark = last

done = False

while not done:

while leftmark <= rightmark and alist[leftmark] <=


pivotvalue:

leftmark = leftmark + 1

while alist[rightmark] >= pivotvalue and rightmark >=


leftmark:

rightmark = rightmark -1

if rightmark < leftmark:

done = True

else:

temp = alist[leftmark]
33

alist[leftmark] = alist[rightmark]

alist[rightmark] = temp

temp = alist[first]

alist[first] = alist[rightmark]

alist[rightmark] = temp

return rightmark

alist = [54,26,93,17,77,31,44,55,20]

quickSort(alist)

print(alist)
34

Output:

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Result:

Thus the above experiment is successfully compiled and

Output is verified.
35

MERGE SORT

Exp No: 12

Date:

Aim:

Write a Python program to sort an array using Merge sort

method.

Algorithm:

1. To sort the entire sequence A[1..n], make the initial


call to the procedure MERGE-SORT(A,1,n).

MERGE-SORT(A,p,r)

1. If p<r

2. Then q=floor[(p + r)/2]

a. MERGE(A, p, q)

b. MERGE(A, q+1, r)

c. MERGE(A, p, q, r)
36

Coding:

def mergeSort(alist):

print("Splitting ",alist)

if len(alist)>1:

mid = len(alist)//2

lefthalf = alist[:mid]

righthalf = alist[mid:]

mergeSort(lefthalf)

mergeSort(righthalf)

i=0

j=0

k=0

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

if lefthalf[i] < righthalf[j]:

alist[k]=lefthalf[i]

i=i+1

else:

alist[k]=righthalf[j]

j=j+1

k=k+1

while i < len(lefthalf):

alist[k]=lefthalf[i]

i=i+1

k=k+1
37

while j < len(righthalf):

alist[k]=righthalf[j]

j=j+1

k=k+1

print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]

mergeSort(alist)

print(alist)
38

Output:

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Result:

Thus the above experiment is successfully compiled and

Output is verified.
39

MATRIX MULTIPLICATION

Exp No: 13

Date:

Aim:

Write a Python program to multiply two matrices

Algorithm:

1. Start

2. Declare variables and initialize necessary variables

3. Enter the element of matrices by row wise using loops

4. Check the number of rows and column of first and second


matrices

5. If number of rows of first matrix is equal to the


number of columns of second matrix, go to step 6.
Otherwise, print matrix multiplication is not possible
and goes to step 3.

6. Multiply the matrices using nested loops.

7. Print the product in matrix from the console output.

8. Stop
40

Coding:

matrix1 = [[1, 2, 3],

[4, 5, 6],

[7, 8, 9]]

matrix2 = [[10, 11, 12, 13],

[14, 15, 16, 17],

[18, 19, 20, 21]]

rmatrix = [[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0]]

for i in range(len(matrix1)):

for j in range(len(matrix2[0])):

for k in range(len(matrix2)):

rmatrix[i][j] += matrix1[i][k] * matrix2[k][j]

for r in rmatrix:

print(r)
41

Output:

101 111 121 132 236 258 280 306 361 385 409 440

Result:

Thus the above experiment is successfully compiled and

Output is verified.
42

WORD COUNT

Exp No: 14

Date:

Aim:

Write a Python program that take command line


arguments(Word Count)

Algorithm:

1. Take the file name from the user

2. Read each line from the file and split the line to from
a list of words

3. Find the length of items in the list and print it.

4. Stop
43

Coding:

fname = input("Enter file name: ")

num_words = 0

with open(fname, 'r') as f:

for line in f:

words = line.split()

num_words += len(words)

print("Number of words:")

print(num_words)
44

Output:

A.txt

=====

Welcome To India

Number of Words 3

Result:

Thus the above experiment is successfully compiled and

Output is verified.
45

FIND THE MOST FREQUENT WORDS

Exp No: 15

Date:

Aim:

Write a Python program to find the most frequent words in


a text read from a file.

Algorithm:

1. Take the file name from the user

2. Read each line from the file and split the line to from
a list of words

3. Use a for loop to traverse through the words in the


list and another for loop to traverse through the
letters in the word.

4. Check if the letter provided by the user and the letter


encountered over iteration is equal and if they are,
increment the letter count.

5. Exit
46

Coding:

from string import punctuation

from operator import itemgetter

N = 10

words = {}

words_gen = (word.strip(punctuation).lower() for line in


open("test.txt")

for word in
line.split())

for word in words_gen:

words[word] = words.get(word, 0) + 1

top_words = sorted(words.iteritems(), key=itemgetter(1),


reverse=True)[:N]

for word, frequency in top_words:

print (word, frequency)


47

Output:

test.txt

=====

Welcome To India India

Welcome 1

To 1

India 2

Result:

Thus the above experiment is successfully compiled and

Output is verified.

You might also like