PYTHON Lab Manual
PYTHON Lab Manual
LAB
CS-506
LAB MANUAL
Syllabus
1) Write aPython program to find GCD oftwo numbers.
2) Write aPython Programto find thesquareroot ofanumberbyNewton’sMethod
3) Write aPython program to find theexponentiation ofanumber.
4) Write aPython Programto find themaximum from a list of numbers.
5) WriteaPython Program to performLinear Search
6) W riteaPythonProgram to performBinarySearch
7) Write aPython Programto perform selection sort.
8) Write aPython Programto perform insertion sort.
9) Write aPython Programto performMerge sort.
10)Write aPython programto find first n primenumbers.
11)Write aPython programto multiplymatrices.
13) To write a Python program to find the most frequent words in a text read from a file.
Aim:
To write aPython program to find GCD oftwo numbers.
Algorithm:
1. Defineafunction named compute GCD()
2. Find thesmallest amongthe two inputs xandy
3. Perform the following step tillsmaller+1
Check if ((x% i==0)and (y%i ==0)), then assign GCD=i
4. Print thevalue ofgcd
Program:
defcomputeGCD(x, y):
if x > y:
smaller = y
else:
smaller = x
fori in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
returngcd
computeGCD(54, 24)
Sample Output:
$pythonmain.py
('TheGCD. of', 54,'and',24, 'is', 6)
Program2:Write a Python Program to find the square root of a number by
Newton’s Method
Aim:
To write aPython Program to find thesquare rootofanumberbyNewton’sMethod.
Algorithm:
1. Define a function named newtonSqrt().
2.Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.)
3. Use a while loop with a condition better!=approxto perform the following,
i. Set approx.=better
ii. Better=0.5*(approx.+n/approx.)
4. Print the value of approx..
Program:
defnewtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx=better
better = 0.5 * (approx + n/approx)
returnapprox
newtonSqrt(100)
Sample Output:
26
Program3: Write aPython programto find theexponentiation ofanumber.
Aim:
To write a Python program to find the exponentiation of anumber.
Algorithm:
1. Define a function named power()
2. Read the values of base and exp
3. Use ‘if’to check if exp is equal to 1 ornot
i. if exp is equal to 1, then return base
ii.if exp is not equal to 1,then return (base*power(base,exp-1))
4. Print the result.
Program:
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))
Sample Output:
Enter base: 7
Enter exponential value: 2
Result:49
Program 4: Write a Python Program to find the maximum from a list of numbers.
Aim:
To write aPython Program to find themaximum from a list of numbers.
Algorithm:
1. Create anemptylist named l
2. Read the value of n
3. Read the elements of thelistuntil n
4. Assign l[0]as maxno
5.If l[i]>maxno then set maxno=l[i]
6.Increment iby1
7. Repeat steps 5-6 until i<n
8. Print thevalue ofmaximum number
Program:
l=[]
n=int(input("enter theupper limit"))
foriin range(0,n):
a=int(input("enterthenumbers"))
l.append(a)
maxno=l[0]
foriin range(0,len(l)):
if l[i]>maxno:
maxno=l[i]
print("Themaximum numberis %d"%maxno)
SampleOutput:
$pythonmain.py
(list of items is: [5, 7, 10, 12, 15])
enteritem to search:7 (item
found at position:, 2)
Program 6: Write a Python Program to perform Binary Search
Aim:
To write a Python Program to perform binary search.
Algorithm:
1. Read the search element
2. Find themiddle element in the sorted list
3. Comparethe searchelement with the middle element
i. if both arematching, printelement found
ii. else then check if thesearchelement is smallerorlarger than the middleelement
4.If thesearchelement is smaller than the middle element, then repeat steps 2 and 3 for the
left sublistof themiddle element
5.If thesearchelement is larger than themiddleelement, then repeat steps2 and 3 forthe
right sublist of the middle element
6. Repeat theprocess untilthe searchelement if found in thelist
7.If element is not found, loop terminates
Program:
# Pythoncodeto implement iterativeBinarySearch.
#Itreturns location ofxin givenarrayarr
# if present, elsereturns-1
defbinarySearch(arr, l, r, x):
while l <= r:
mid =l + (r -l)/2;
# Check if xis present at mid
if arr[mid]==x:
return mid
#If xis greater, ignoreleft half
elifarr[mid]<x:
l = mid + 1
#If xis smaller, ignoreright half
else:
r =mid -1
#Ifwereach here, then the element
# was not present
return -1
# Test array
arr=[2, 3, 4, 10, 40 ]
x=4
# Function call
result=binarySearch(arr, 0, len(arr)-1, x)
ifresult!= -1:
print"Element is present at index% d"% result
else: else
print"Element is not present in array"
Sample Output:
$pythonmain.py
Element is present at index 2
Program7: Write a Python Program to perform selection sort.
Aim:
To write aPython Program to perform selection sort.
Algorithm:
1. Create afunction named selectionsort
2.Initialisepos=0
3.If alist[location]>alist[pos]then perform the followingtilli+1,
4. Set pos=location
5. Swap alist[i]and alist[pos]
6. Print thesorted list
Program:
defselectionSort(alist):
foriin range(len(alist)-1,0,-1):
pos=0
forlocation in range(1,i+1):
ifalist[location]>alist[pos]:
pos=location
temp =alist[i]
alist[i]=alist[pos]
alist[pos]=temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
SampleOutput:
$pythonmain.py
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Program8: Write aPython Programtoperforminsertionsort.
Aim:
To write aPython Program to perform insertion sort.
Algorithm:
1. Create afunction named insertionsort
2.Initialisecurrentvalue=alist[index]and position=index
3. while position>0 and alist[position-1]>currentvalue, perform the followingtilllen(alist)
4. alist[position]=alist[position-1]
5. position =position-1
6. alist[position]=currentvalue
7. Print thesorted list
Program:
definsertionSort(alist):
forindexin 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)
Sample Output:
$python main.py
[20, 54, 54, 54, 54, 54, 93, 93, 93]
Program9: Write aPython ProgramtoperformMerge sort.
Aim:
To write aPython Program to perform Mergesort.
Algorithm:
1. Create afunction named mergesort
2. Find themid of thelist
3. Assign lefthalf =alist[:mid]and righthalf=alist[mid:]
4.Initialisei=j=k=0
5. whilei<len(lefthalf)and j <len(righthalf), perform the following if
lefthalf[i]<righthalf[j]:
alist[k]=lefthalf[i]
Increment i
else
alist[k]=righthalf[j]
Increment j
Increment k
6. whilei<len(lefthalf),perform thefollowing
alist[k]=lefthalf[i]
Increment i
Increment k
7. while j <len(righthalf), perform thefollowing
alist[k]=righthalf[j]
Increment j
Increment k
8. Print thesorted list
Program:
# Python programforimplementation of MergeSort
# Merges two subarraysofarr[].
# First subarrayis arr[l..m]
# Second subarrayis arr[m+1..r]
def merge(arr, l, m, r):
n1 =m -l + 1
n2 = r-m
# createtemp arrays
L=[0]* (n1) R
=[0]* (n2)
mergeSort(arr,0,n-1)
print("\n\nSortedarrayis")
foriin range(n):
print("%d"%arr[i]),
Sample Output:
$python main.py
Given arrayis
12 11 13 5 6 7
Sorted arrayis
5 6 7 11 12 13
Program10: WriteaPython programto find first nprimenumbers.
Aim:
To write aPython program to find first n primenumbers.
Algorithm:
1. Read the value of n
2. fornumin range(0,n + 1), perform the following
3. ifnum%i is 0 then break
else printthe value ofnum
4. Repeat step 3 for i in range(2,num)
Program:
n =int(input("Enter theupper limit: "))
print("Primenumbersare")
fornumin range(0,n +1):
# primenumbers aregreater than 1
if num>1:
foriin range(2,num):
if(num % i) ==0:
break
else:
print(num)
Sample Output:
$python main.py
Enter theupper limit:20
Primenumbers are
2
3
5
7
11
13
17
19
Program11: Write a Python programto multiplymatrices.
Aim:
Algorithm:
To write a Python program to multiply matrices.
1. Definetwo matrices Xand Y
2. Create aresultant matrixnamed ‘result’
3. foriin range(len(X)):
i. forj in range(len(Y[0])):
a) fork in range(len(Y))
b)result[i][j]+=X[i][k]* Y[k][j]
4. forrin result, print thevalue ofr
Program:
X =[[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y =[[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
foriin range(len(X)):
forj in range(len(Y[0])):
fork in range(len(Y)):
result[i][j]+=X[i][k]* Y[k][j]
forrin result:
print(r)
Sample Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
To write a Python program for command line arguments.
What is sys.argv?
sys.argv is the list of commandline arguments passed to the Python program. argv represents all the
items that come along via the command line input, it's basically an array holding the command line
arguments of our program. Don't forget that the counting starts at zero (0) not one (1).
import sys
for x in sys.argv:
print "Argument: ", x
Output:
>python ex.py
Argument: ex.py
In this program, we need to find the most repeated word present in given text file. This can be
done by opening a file in read mode using file pointer. Read the file line by line. Split a line at
a time and store in an array. Iterate through the array and find the frequency of each word and
compare the frequency with maxcount. If frequency is greater than maxcount then store the
frequency in maxcount and corresponding word that in variable word. The content of data.txt
file used in the program is shown below.
1. data.txt
Algorithm
1. Variable maxCount will store the count of most repeated word.
2. Open a file in read mode using file pointer.
3. Read a line from file. Convert each line into lowercase and remove the punctuation
marks.
4. Split the line into words and store it in an array.
5. Use two loops to iterate through the array. Outer loop will select a word which needs to
be count. Inner loop will match the selected word with rest of the array. If match found,
increment count by 1.
6. If count is greater than maxCount then, store value of count in maxCount and
corresponding word in variable word.
7. At the end, maxCount will hold the maximum count and variable word will hold most
repeated word.
count = 0;
word = "";
maxCount = 0;
words = [];
Output:
importpygame
import math
import sys
pygame.init()
clock = pygame.time.Clock()
while(True):
for event in pygame.event.get():
ifevent.type == pygame.QUIT:
sys.exit()
xRadius = 250
yRadius = 100
pygame.display.flip()
clock.tick(5)
To write a Python program to bouncing ball in Pygame.
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
ifevent.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
ifballrect.left< 0 or ballrect.right> width:
speed[0] = -speed[0]
ifballrect.top< 0 or ballrect.bottom> height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
VIVAVOCEQUESTIONS
1. What it thesyntaxof print function?
2. What is the usageof input function?
3. Defineavariable.
4. What is typeconversion?
5. Mention the data typesin Python
6. What arethe attributesof the complexdatatype?
7. Mention a fewescapesequences.
8. Define anexpression
9. What is the usageof ** operator in Python?
10. Givethe syntaxof if else statement.
11. Givethe syntaxof forstatement.
12. Howis rangefunction used in for?
13. Givethe syntaxof while statement.
14. What aremultiwayif statements?
15. Howis random numbersgenerated?
16. Defineafunction.
17. Givethe syntaxof function.
18. What arethe types ofarguments in function.?
19. What is a recursive function?
20. What are anonymousfunctions?
21. What aredefaultarguments?
22. What arevariable length arguments?
23. What arekeyword arguments?
24. Mention theuse of map().
25. Mention theuse of filter().
26. Mention theuse of reduce().
27. Defineastring.
28. Howis stringslicing done?
29. What is the usageofrepetition operator?
30. Howis stringconcatenation doneusing+operator>
31. Mention somestring methods
32. Howis length ofastringfound?
33. Howis a string converted to its upper case?
34. `Differentiate isalpha() and isdigit().
35. What is the useof split()?
36. Defineafile.
37. Givethe syntaxforopening a file.
38. Givethe syntaxfor closinga file.
39. Howis readingoffile done?
40. Howis writingoffiledone?
41. What is a list?
42.Lists aremutable-Justify.
43. Howis a list created?
44. How canalist be sorted?
45. How are elements appended to thelist?
46. Howis insert()usedin list?
47. What is the usageofpop()in list?
48. Defineatuple.
49. Aretuples mutable orimmutable?
50. Mention theuse of return statement.
51. What is a Boolean function?
52. Howis main function defined?
53. What is a dictionary?
54. How aretuples created?
55. Howis a dictionarycreated?
56. Howto print the keysof adictionary?
57. Howto print the values ofadictionary?
58. Howis del statementused?
59. Can tuple elements bedeleted?
60. What is Python interpreter?
61. Whyis Python calledan interpreted language?
62. Mention some features of Python
63. What is PythonIDLE?
64. Mention some rules fornaming an identifier inPython.
65. Givepoints about Python Numbers.
66. What is bool datatype?
67. Give examples of mathematical functions.
68. What is stringformattingoperator?
69. Mention about membership operators inPython.
70. Howis expression evaluated in Python?
71. What arethe loop control statements in Python?
72. What is the useof break statement?
73. What is the useof continuestatement?
74. What is the useof pass statement?
75. What is assert statement?
76. Differentiate fruitfulfunction s and void functions.
77. What are required arguments ?
78. Differentiate pass byvalue and pass byreference.
79. Mention few advantages of function.
80. Howis lambda function used?
81. What is a local variable?
82. What areglobal variables?
83. What arePython decorators?
84. Arestrings mutable or immutable?
85. What is join()?
86. What is replace() method?
87. What is list comprehension?
88. Definemultidimensional list.
89. Howto create lists usingrange()?
90. What is swapcase()method?
91. What is linear search?
92. Howis binarysearchdone?
93. Howis mergesort performed?
94. What is sorting?
95. Howis insertion sort done?
96. Howis selection sortdone?
97. What are command line arguments?
98. Name some built in functions with dictionary.
99. What is an exception?
100. Howis exception handled in python?
******************************* TheEnd***********************************