You are on page 1of 54

INTRODUCTION TO PROGRAMMING WITH

PYTHON LAB

Prepared By

IRANIYA PANDIYAN M

Dept of Computer Science and Engineering

Jaya Engineering College

Thiruninravur
1. Compute the GCD of two numbers

Aim:

To Compute the Greatest Common Divsor of two numbers using Python programming

Program :

def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
Output:
Result :
2.Find the square root of a number (Newtons method)

Aim:
To Compute the Greatest Common Divsor of two numbers using
Python programming

Program

# Note: change this value for a different

result num = 8

# uncomment to take the input from the


user #num = float(input('Enter a number:
')) num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Output:
Result :
3.Exponentiation (power of a number)

Aim :
To Compute the Greatest Common Divsor of two numbers using
Python programming

Program :

#!/usr/bin/python

import math # This will import math module

print "math.exp(-45.17) : ", math.exp(-45.17)


print "math.exp(100.12) : ", math.exp(100.12)
print "math.exp(100.72) : ", math.exp(100.72)
print "math.exp(119L) : ", math.exp(119L)
print "math.exp(math.pi) : ", math.exp(math.pi)
Output:
Result :
4 a. Linear search in Python

Aim :
To Perform a Linear Search in Python Programming

Program :

items = [5, 7, 10, 12, 15]

print("list of items is", items)

x = int(input("enter item to search:"))

i = flag = 0

while i < len(items):


if items[i] == x:
flag = 1
break

i=i+1

if flag == 1:
print("item found at position:", i + 1)
else:
print("item not found")
~
Output:
Result :
4.b ) Binaray Search

Aim :

To Perform a Binary Search using Python Programming

Program

import random

anum = 9 # number to search for size = 10 #


size of random array
array = random.sample(list(range(1, 20)), size) # get some random numbers
array = sorted(array) # sorted() returns a new list
#array.sort() # sort() sorts in-place print(anum,
array) # show us what you've got

# Search for number in array

def binary_search(number, array, lo, hi):

if hi < lo: return -1 # no more numbers


mid = (lo + hi) // 2 # midpoint in array
if number == array[mid]:
return mid # number found here
elif number < array[mid]:
return binary_search(number, array, lo, mid - 1) # try left of here
else:
return binary_search(number, array, mid + 1, hi) # try above here

def my_search(anum, array): # convenience interface to binary_search()


return binary_search(anum, array, 0, len(array) - 1)

pos = my_search(anum, array)


if pos < 0:
print("not found")
else:
print("found at position", pos)
Output :
Result :
5. First N Prime Numbers

Aim: To Compute the First N Prime numbers using Python programming

Program :

def prime(n):
def z(x):
if x :return True
return False
num1=range(0,n+1); num2=int(n**0.5)
+1 for k in range(2,num2):
num0=range(k,n+1,k);del num0[0]
for i in num0:
num1[i]=0
return filter(z, num1)

print prime(102)
Result :
6.Find the maximum of a list of numbers

Aim :
To find the maximum of a list of numbers using Python Programming

Program

#!/usr/bin/python

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]

print "Max value element : ", max(list1)


print "Max value element : ", max(list2)
Output:
Result :
7. a) Selection Sort

Aim :

To Perform a Selection Sorting in Python Programming

Program :

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)
~
Output :
Result :
7. b) Insertion Sort

Aim :

To Perform Insertion Sorting in Python Programming

Program:

def sort_insertion(my_list):

for i in range(1,len(my_list)):

val_current = my_list[i]
pos = i

while((pos > 0) and (my_list[pos-1] > val_current)):


my_list[pos] = my_list[pos-1]
pos = pos-1

if pos != i:
my_list[pos] = val_current

return my_list

if __name__ == "__main__":

my_list = [54,26,93,17,77,31,44,55,20]
print(my_list)
print sort_insertion(my_list)
Output :
Result :
8. Removing all the duplicate elements in a list

Aim :

By using Python Commands to remove all the duplicate elements in a list

Program:

ram@ram-Inspiron-3541:~ $ python3.4
Python 3.4.3 (default, Nov 17 2016,
01:11:57) [GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> t = [1,2,3,1,2,5,6,7,8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1,2]
>>> list(set(t)-set(s))
[8, 3, 5, 6, 7]
Output:

Result :
9 a. Merge Sort

Aim :

To Perform Merge Sorting Using Python Programming language

Program :

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

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)

Output :
Result :
9.b) Quick Sort

Aim:

To Perform Quick Sorting Using Python Programming Language

Program :

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

Output :
Result :
10. Program to multiply two matrices using nested loops

Aim :

To Perform Matrix Multiplication in Python Programming

Program:

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

# 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:
Result :
11. Commandline Arguments

Aim :

To Perform Commandline Arguments using Python Programming

Program:

#!/usr/bin/python

import sys, getopt

def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o
<outputfile>' sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o
<outputfile>' sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile

if __name__ == "__main__":
main(sys.argv[1:])
Output:

Result :
12. Find the most frequent words in a text read from a file

Aim :

To find the most frequent words in a text read from a file using python

Program :

import string

def compareItems((w1,c1), (w2,c2)):

if c1 > c2:

return - 1

elif c1 == c2:

return cmp(w1, w2)

else:

return 1

def main():

print "This program analyzes word frequency in a file"

print "and prints a report on the n most frequent words.\n"

fname = raw_input("File to analyze: ")

text = open(fname,'r').read()

text = string.lower(text)
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':

text = string.replace(text, ch, ' ')

words = string.split(text)

counts = {}

for w in words:

counts[w] = counts.get(w,0) + 1

n = input("Output analysis of how many words? ")

items = counts.items()

items.sort(compareItems)

for i in range(n):

print "%-10s%5d" % items[i]

if __name__ == '__main__': main()

Sample Output:

Create a txt file

example : Obama2009.txt

In the txt file give the input

like : hi hw r u

Then run the python as

python filename.py
Result :
References

1.www.interactivepython.org

2.www.tutorialspoint.com/python

3.www.stackoverflow.com

4.www.programiz.com/pythonprogramming

5.www.python3codes.com/binary-search

6.www.code.runnable.com/python