0% found this document useful (0 votes)
69 views13 pages

Compute The GCD of Two Numbers

The document provides code snippets for several algorithms and data structures including: - Computing the greatest common divisor (GCD) of two numbers - Finding the square root of a number using Newton's method - Exponentiation to calculate a number to a given power - Finding the maximum value in a list - Linear and binary search algorithms - Common sorting algorithms like selection, insertion, merge, and bubble sort - Matrix multiplication - A word counting program that takes a filename as a command line argument - Finding the most frequent words in a text file

Uploaded by

abishiek vasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views13 pages

Compute The GCD of Two Numbers

The document provides code snippets for several algorithms and data structures including: - Computing the greatest common divisor (GCD) of two numbers - Finding the square root of a number using Newton's method - Exponentiation to calculate a number to a given power - Finding the maximum value in a list - Linear and binary search algorithms - Common sorting algorithms like selection, insertion, merge, and bubble sort - Matrix multiplication - A word counting program that takes a filename as a command line argument - Finding the most frequent words in a text file

Uploaded by

abishiek vasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Compute the GCD of two numbers.

PROGRAM:

D1=int(input(“enter number”))

D2=int(input(“enter number”))

Rem=d1%d2

While rem!=0:

D1=d2

D2=rem

Rem=d1%d2

Print(“gcd of given numbers”,d2)

OUPUT:

Enter number 2

Enter number 4

Gcd of given numbers 2


Find the square root of a number (Newton's method)

PROGRAM:

def newtonSqrt(n, a):

approx = 0.5 * n

for i in range(a):

betterapprox = 0.5 * (approx + n/approx)

approx = betterapprox

return betterapprox

print(newtonSqrt(10, 3))

print(newtonSqrt(10, 5))

print(newtonSqrt(10, 10))

Output:

3.162319422150883

3.162277660168379

3.162277660168379
Exponentiation (power of a number)

PROGRAM:

N=int(input(“enter number:”))

E=int(input(“enter exponent:”))

R=n

For I in range(1,e):

R=n*r

Print r

OUTPUT:

Enter number:5

Enter exponent: 3

125
Find the maximum of a list of numbers

PROGRAM:

Def max_num_in_list(list):

Max=list(0)

For a in list:

If a > max:

Max=a

Return max

Print max_num_in_list(1,2,-8,0)

OUTPUT:

2
Linear search

PROGRAM:

def sequential Search(dlist, item):

pos = 0

found = False

while pos < len(dlist) and not found:

if dlist[pos] == item:

found = True

else:

pos = pos+1

return found

linearlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]

print(sequential Search(linearlist, 3))

print(sequential Search(linearlist, 13))

OUTPUT:

False

True
Binary Search

PROGRAM:

def binarySearch(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

blist = [0, 1, 2, 8, 13, 17, 19, 32, 42]


print(binarySearch(blist, -1))
print(binarySearch(blist, 13))

OUTPUT:

False
True
Selection sort

PROGRAM:

def selectionsort(nlist):
print("intial list:",nlist)
for i in range(len(nlist)):
print(nlist)
minIndex=i
j=i+1
while(j < len(nlist)):
if(nlist[j] < nlist[minIndex]):
minIndex = j
j+=1
nlist[i], nlist[minIndex] = nlist[minIndex], nlist[i]
print("sorted list",nlist)
nlist1 = [12,1,3,2,7,-100]
selectionsort(nlist1)

OUTPUT:

-100 1 2 3 7 12
Insertion Sort

PROGRAM:

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)

OUTPUT:

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

PROGRAM:

def mergesort(lefthalf,righthalf):
result = []
i,j,k = 0, 0 ,0
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i] <= righthalf[j]:
result.append(lefthalf[i])
i+=1
k=k+1
else:
result.append(righthalf[j])
j+=1
k=k+1
result += lefthalf[i:]
result += righthalf[j:]
return result
defmerge(alist):
if(len(alist) <= 1):
return alist
if(len(alist)>1):
mid = int(len(alist)/2)
lefthalf = merge(alist[:mid])
righthalf = merge(alist[mid:])
return mergesort(lefthalf,righthalf)

arr = [1,2,-1,0,9,65,7,3,4,1,2]
print(mergesort(arr))

OUTPUT:

-1, 0, 1, 1, 2,3, 4, 7,9,65


Multiply matrices

PROGRAM:

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]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

OUTPUT:

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]
Programs that take command line arguments(word count)

PROGRAM:

import sys
if len(sys.argv)!=2:
print "Error: Filename missing"
sys.exit(1)
fname = sys.argv[1]
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)

OUTPUT:

sample.txt
Hello!
Welcome to Python Programming

>>> python wordcount.py sample.txt


Number of words: 5
Find the most frequent words in a text read from a file.

PROGRAM:

fr = open("test.txt","r")
wordcount = {}
for word in fr.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print(k, v)
fr.close()

OUTPUT:

sample.txt
I like python programming.
I like C programming.

>>> python frequentwords.py


I2
line 2
python 1
programming. 2
C1

You might also like