0% found this document useful (0 votes)
82 views19 pages

To Write A Program To Compute GCD of Two Number

The document contains 15 code snippets demonstrating various Python programming concepts and algorithms, including: 1) Computing the greatest common divisor (GCD) of two numbers using Euclid's algorithm and a recursive function. 2) Finding the square root of a number using Newton's method for numerical approximation with iterative calculations. 3) Calculating the exponentiation or power of a number using recursion. 4) Sorting lists using selection sort, insertion sort, merge sort, and quick sort algorithms. 5) Searching lists using linear/sequential search and binary search algorithms. 6) Additional examples include prime number generation, matrix multiplication, word counting in text, and removing duplicate elements from a

Uploaded by

THIYAGARAJAN v
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
82 views19 pages

To Write A Program To Compute GCD of Two Number

The document contains 15 code snippets demonstrating various Python programming concepts and algorithms, including: 1) Computing the greatest common divisor (GCD) of two numbers using Euclid's algorithm and a recursive function. 2) Finding the square root of a number using Newton's method for numerical approximation with iterative calculations. 3) Calculating the exponentiation or power of a number using recursion. 4) Sorting lists using selection sort, insertion sort, merge sort, and quick sort algorithms. 5) Searching lists using linear/sequential search and binary search algorithms. 6) Additional examples include prime number generation, matrix multiplication, word counting in text, and removing duplicate elements from a

Uploaded by

THIYAGARAJAN v
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

1.

To write a program to compute GCD of two number

Program:
deffunc_GCD(X, Y):

if X>Y:

small=Y

else:

small=X

fori in range(1,small+1):

if(( X % i == 0)and(Y % i == 0)):

GCD=i

return GCD

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

num2 = int(input("Enter second number:" ))

print ("The GCD of", num1,"and",num2,"is", func_GCD(num1, num2))

Output:
Enter first number:15

Enter second number:12

('The GCD of', 15, 'and', 12, 'is', 3)


1. EUCLID’S Method
Program:
defcomputeGCD(x,y):

while(y):

x,y = y, x% y

return x

print (computeGCD(300,400))

Output:
100
2.To write a program to find the square root of a number

(Newton’s Method)
Program:
defnewtonsqrt(n, iteration):

approx = 0.5 * n

fori in range(iteration):

betterapprox = 0.5 * (approx + n/approx)

approx = betterapprox

returnbetterapprox

print(newtonsqrt(10, 3))

print(newtonsqrt(10, 5))

print(newtonsqrt(10, 10))

Output:
3.16231942215

3.16227766017

3.16227766017
3.To write a program to find the Exponentiation of a number
(Power of a Number)
Program:
import math

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

print(math.pow(100,2),math.pow(100,2))

Output:
enter base: 4

enter exponential value: 2

('result:', 16)

(10000.0, 10000.0)
4.Find the maximum of a list of number
Program:
numlist =[78, 6, 74, 43, 41]

maxnum = numlist[0]

fori in numlist:

ifi>maxnum:

maxnum +i

print("the maximum element of the list is :" ,maxnum)

print("the maximum element using max function :" ,max(numlist))

Output:
('the maximum element of the list is :', 78)

('the maximum element using max function :', 78)


5.To search an element using Linear or sequential
Program:
my_data = [89,45,9,21,34]

num =int(input("enter search number = "))

fori in range(0,len(my_data)):

ifnum == my_data[i]:

print("item is location at the position = " ,i)

Output:
enter search number = 45

('item is location at the position = ', 1)


6. To write a program to search an element using binary search

Program:
defbinary_search(item_list,item):
first= 0
last=len(item_list)-1
found =False
while(first<=last and not found):
mid = (first + last)//2
ifitem_list[mid] == item :
found = True
print("Element found at location=",mid)
else:
if item <item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found

print ("Search the element 77 in the list 1:")


print(binary_search([6,12,17,23,38,45,77,84,90],45))
print ("Search the element 77 in the list 2:")
print(binary_search([16,12,17,23,38,45,77,84,90],5))

Output:
Search the element 77 in the list 1:
('Element found at location=', 5)
True
Search the element 77 in the list 2:
False
7. To write a program to sort list of element using selection sort

Program:
def swap( Tlist, ind1, ind2 ):
tmp=Tlist[ind1]
Tlist[ind1]=Tlist[ind2]
Tlist[ind2]=tmp

Nos_List=[7,2,5,1,29,6,4,19,11]
print("BeforeSorting :",Nos_List)

fori in range(len(Nos_List)-1,0,-1):
Minposition=0

for k in range( 1, i+1):


ifNos_List[k] <Nos_List[Minposition]:
Minposition=k
swap(Nos_List,Minposition,i)

print ("After Sorting :",Nos_List)

Output:
('BeforeSorting :', [7, 2, 5, 1, 29, 6, 4, 19, 11])
('After Sorting :', [7, 2, 5, 1, 29, 6, 4, 19, 11])
8. To write a program to sort list of element using Insertion sort

Program:
Nos_List=[54,26,93,17,77,31,44,55,20]
print("BeforeSorting:",Nos_List)

fori in range(1,len(Nos_List)):
tmp=Nos_List[i]

position=i

while position>0 and tmp<Nos_List[position-1]:

Nos_List[position]=Nos_List[position-1]

position-=1

Nos_List[position]=tmp

print("AfterSorting:",Nos_List)

Output:
('BeforeSorting:', [54, 26, 93, 17, 77, 31, 44, 55, 20])

('AfterSorting:', [54, 26, 93, 17, 20, 77, 31, 44, 55])
9. To write a program to sort list of element using Merge Sort

Program:
Nos_List=[54,26,93,17,77,31,44,55,20]
print ("BeforeSorting : ",Nos_List)
for i in range( 1, len(Nos_List)):
tmp=Nos_List[i]
Position=i

while Position>0 and tmp<Nos_List[Position- 1]:


Nos_List[Position]=Nos_List [Position- 1]
Position -=1
Nos_List[Position]= tmp
print("AfterSorting : ",Nos_List)

Output:
BeforeSorting : [54, 26, 93, 17, 77, 31, 44, 55, 20]
AfterSorting : [26, 54, 93, 17, 77, 31, 44, 55, 20]
AfterSorting : [26, 54, 17, 93, 77, 31, 44, 55, 20]
AfterSorting : [26, 17, 54, 93, 77, 31, 44, 55, 20]
AfterSorting : [17, 26, 54, 93, 77, 31, 44, 55, 20]
AfterSorting : [17, 26, 54, 77, 93, 31, 44, 55, 20]
AfterSorting : [17, 26, 54, 77, 31, 93, 44, 55, 20]
AfterSorting : [17, 26, 54, 31, 77, 93, 44, 55, 20]
AfterSorting : [17, 26, 31, 54, 77, 93, 44, 55, 20]
AfterSorting : [17, 26, 31, 54, 77, 44, 93, 55, 20]
AfterSorting : [17, 26, 31, 54, 44, 77, 93, 55, 20]
AfterSorting : [17, 26, 31, 44, 54, 77, 93, 55, 20]
AfterSorting : [17, 26, 31, 44, 54, 77, 55, 93, 20]
AfterSorting : [17, 26, 31, 44, 54, 55, 77, 93, 20]
AfterSorting : [17, 26, 31, 44, 54, 55, 77, 20, 93]
AfterSorting : [17, 26, 31, 44, 54, 55, 20, 77, 93]
AfterSorting : [17, 26, 31, 44, 54, 20, 55, 77, 93]
AfterSorting : [17, 26, 31, 44, 20, 54, 55, 77, 93]
AfterSorting : [17, 26, 31, 20, 44, 54, 55, 77, 93]
AfterSorting : [17, 26, 20, 31, 44, 54, 55, 77, 93]
AfterSorting : [17, 20, 26, 31, 44, 54, 55, 77, 93]
10. To print first n prime number
Program:
N=('raw_input''Enter the no N:')

count = 0
CheckNo = 2

defIsPrime(potentialprime):
divisor = 2
while divisor <= potentialprime:
ifpotentialprime == 2:
return True
elif(potentialprime)%divisor == 0:
return False
break
whilepotentialprime%divisor !=0:
ifpotentialprime - divisor > 1:
divisor +=1
else:
return True

while count <int(10):


ifIsPrime(CheckNo) == True:
print('Prime#' + str(count + 1), 'is', CheckNo)
count += 1
CheckNo += 1
else:
CheckNo += 1

Output:
('Prime#1', 'is', 2)
('Prime#2', 'is', 3)
('Prime#3', 'is', 5)
('Prime#4', 'is', 7)
('Prime#5', 'is', 11)
('Prime#6', 'is', 13)
('Prime#7', 'is', 17)
('Prime#8', 'is', 19)
('Prime#9', 'is', 23)
('Prime#10', 'is', 29)
11. Matrix Multiplication

Program:
print("matrix multiplication")
X=[]
for i in range(3):
m1=[]
for j in range(3):
print ("Enter element for[",i,",",j,"]")
m1.append(int(input("")))
X.append(m1)

print ("First matrix")


for r in X:
print (r)

Y=[]
for i in range (3):
n1=[]
for j in range (3):
print ("Enter element for[",i,",",j,"]")
n1.append(int(input("")))
Y.append(n1)

print ("Second matrix")


for r in Y:
print (r)

product=[[0,0,0],[0,0,0],[0,0,0]]

for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
product[i][j]+=X[i][k]*Y[k][j]

print ("Product of two matrices")


for r in product:
print (r)

Output:

matrix multiplication
Enter element for[ 0 , 0 ]
6
Enter element for[ 0 , 1 ]
8
Enter element for[ 0 , 2 ]
9
Enter element for[ 1 , 0 ]
4
Enter element for[ 1 , 1 ]
2
Enter element for[ 1 , 2 ]
3
Enter element for[ 2 , 0 ]
5
Enter element for[ 2 , 1 ]
1
Enter element for[ 2 , 2 ]
8
First matrix
[6, 8, 9]
[4, 2, 3]
[5, 1, 8]
Enter element for[ 0 , 0 ]
1
Enter element for[ 0 , 1 ]
0
Enter element for[ 0 , 2 ]
0
Enter element for[ 1 , 0 ]
0
Enter element for[ 1 , 1 ]
1
Enter element for[ 1 , 2 ]
0
Enter element for[ 2 , 0 ]
0
Enter element for[ 2 , 1 ]
0
Enter element for[ 2 , 2 ]
1
Second matrix
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
Product of two matrices
[6, 8, 9]
[4, 2, 3]
[5, 1, 8]
12. Program that take command line argument (word count)

Program:
import sys

from collections import Counter

lines = open(sys.argv[0], 'r').readlines()

c = Counter()

for line in lines:

for work in line.strip().split():

c.update(work)

forind in c:

print (ind, c[ind])

Output:
('"', 6)
("'", 3)
(')', 8)
('(', 8)
(',', 3)
('.', 6)
('1', 10)
('0', 3)
('3', 5)
('2', 9)
('5', 3)
('4', 1)
('7', 4)
('6', 2)
('9', 1)
('8', 1)
(':', 4)
('=', 3)
('C', 3)
('[', 3)
(']', 3)
('a', 4)
('c', 7)
('e', 12)
('d', 6)
('g', 2)
('f', 5)
('i', 18)
('k', 3)
('m', 4)
('l', 9)
('o', 14)
('n', 17)
('p', 8)
('s', 11)
('r', 16)
('u', 4)
('t', 10)
('w', 3)
('v', 2)
('y', 3)
13. Read a most frequent words in text file

Program:
from collections import Counter
with open('myfile.txt')as fin:
counter=Counter(fin.read().strip().split())
Words=counter.most_common()
print("Frequency of the each word in the file:")
for i in Words:
print (i)

#myfile.txt
#hai hello how are you
#all are welcome
#welcome you all

Output:
Frequency of the each word in the file:
('are', 2)
('you', 2)
('all', 2)
('welcome', 2)
('hai', 1)
('hello', 1)
('how', 1) ('hello', 1)
14. Remove all the duplicate element in a list
Program:
Nos_List=[54,26,93,17,77,31,44,55,20]
print ("BeforeSorting : ",Nos_List)
for i in range( 1, len(Nos_List)):
tmp=Nos_List[i]
Position=i

while Position>0 and tmp<Nos_List[Position- 1]:


Nos_List[Position]=Nos_List [Position- 1]
Position -=1
Nos_List[Position]= tmp
print("AfterSorting : ",Nos_List)

Output:
Original List [31, 2, 1, 14, 5, 6, 2, 8, 9, 3, 2, 1, 6, 31, 2]
Using setdefault method and preserving order- New List = [31, 2, 1, 14, 5, 6, 8, 9, 3]
Using Set and without order- New List= [1, 2, 3, 5, 6, 8, 9, 14, 31]
15. To Write a program to sort list of element using Quick Sort
Program:
def partition(sort_list, low, high):
i = (low -1)
pivot = sort_list[high]
for j in range(low, high):
if sort_list[j] <= pivot:
i += 1
sort_list[i], sort_list[j] = sort_list[j], sort_list[i]
sort_list[i+1],sort_list[high] = sort_list[high], sort_list[i+1]
return (i+1)

def quick_sort(sort_list, low, high):


if low < high:
pi = partition(sort_list, low, high)
quick_sort(sort_list, low, pi-1)
quick_sort(sort_list, pi+1, high)
lst = []
size = int(input("Enter size of the list: "))
for i in range(size):
elements = int(input("Enter an element"))
lst.append(elements)
low = 0
high = len(lst) - 1
quick_sort(lst, low, high)
print(lst)

Output:
Enter size of the list: 9
Enter an element8
Enter an element9
Enter an element6
Enter an element2
Enter an element4
Enter an element1
Enter an element3
Enter an element5
Enter an element7
[1, 2, 3, 4, 5, 6, 7, 8, 9]

You might also like