Python Lab Manual
Python Lab Manual
code:
# Python program to swap two variables
output:
Program 2: Swapping two numbers without using
temporary variable
# Python program to swap two variables
code:
def circulate(A,N):
for(I in range(1,N+1));
B=A[i:]+A[:i]
print(“circulation”,I”,=”,B)
return
output
1c. Aim: Write a program to compute distance between two points taking input from the user
(Pythagorean Theorem).
Description: The Pythagorean theorem is the basis for computing distance between two points. Let
(x1,y1) and (x2,y2) be the co-ordinates of points on xy-plane. From Pythagorean theorem, the distance
between two points is calculated using the formulae:
Algorithm:
Step1: Start
Step4: Calculate the distance using the formulae math.sqrt ( (x2 - x1)**2 + (y2 - y1)**2 ) and store the
result in distance
Step6: Stop
Code:-
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
Output:
OBJECTIVES:
PROCEDURE:
a. Create: Open a new file in Python shell, write a program and save the program with .py extension.
SOURCE CODE:
a=int(input())
if(a%2==0):
print("Even")
else: print("Odd")
Input: 4
Output: Even 10
a=int(input())
k=1;
for i in range(1,a+1):
k=k*i;
input: 5
for i in range(2,100):
c=0;
for j in range(1,i+1):
if(i%j==0):
c=c+1 if(c<=2):
Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
else:
print("Either any two values or all the three values are equal")
D) Write a python Program to read a number and display corresponding day using if_elif_else?
if weekday == 1 :
print("\nMonday");
elif weekday == 2 :
print("\nTuesday")
elif(weekday == 3) :
print("\nWednesday")
elif(weekday == 4) :
print("\nThursday")
elif(weekday == 5) :
print("\nFriday")
elif(weekday == 6) :
print("\nSaturday")
elif (weekday == 7) :
print("\nSunday")
else :
Algorithm:
1.Read the search element
2.Find the middle element in the sorted list
3.Compare the search element with the middle element
a. if both are matching, print elementfound
b. else then check if the search element is smaller or larger
than the middle element
4.If the search element is smaller than the middle element, then
repeat steps 2 and 3 for the left sublist of the middle element
5. If the search element is larger than the middle element, then
repeat steps 2 and 3 for the right sublist of the middle element
6.Repeat the process until the search element if found in the list
7. If element is not found, loop terminates
Program:
def bsearch(alist,item):
first = 0
last =len(alist)-1
found = False
mid=int((first+last)/2)
while first<=last and not found:
if alist[mid]==item:
found = True
print("element found in position",mid)
else:
if item<alist[mid]:
last = mid-1
else:
first = mid+mid-1
mid=int((first+last)/2)
if found == False:
print("Element not found")
return found
a=[]
n=int(input("Enter upper limit:"))
print("Enter",n,"numbers")
for i in range(0,n):
e=int(input())
a.append(e)
x=int(input("Enter element to search"))
bsearch(a,x)
Sample Output:
Enter upper limit:10
Enter 10 numbers
12
13
14
15
16
23
26
28
31
35
Enter element to search31
element found in position 8
Enter upper limit:5
Enter 5 numbers
11
17
21
27
32
Enter element to search31
Element not found
Result:
Thus the Python Program to perform binary search is executed
successfully and the output is verified.
4. 4: Selection sort, Insertion sort
4.a) SELECTION SORT
Aim:
To write a Python Program to perform selection sort.
Algorithm:
1.Create a function named selectionsort
2.Initialise pos=0
3.If alist[location]>alist[pos] then perform the following till i+1,
4.Set pos=location
5.Swap alist[i] and alist[pos]
6. Print the sorted list
Program:
def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
pos = 0
for location in range(1,i+1):
if alist[location]>alist[pos]:
pos=location
temp = alist[i]
alist[i]=alist[pos]
alist[pos]=temp
alist = []
n=int(input("enter the upper limit"))
print("enter",n,"numbers")
for i in range(0,n):
x=int(input())
alist.append(x)
selectionSort(alist)
print(“The Sorted list are”)
print(alist)
Sample Output:
enter the upper limit5
enter 5 numbers
14
12
35
48
95
The sorted list are
[12, 14, 35, 48, 95]
Result: Thus the Python Program to perform selection sort is
successfully executed and the output is verified.
4. b ) INSERTION SORT
Aim: To write a Python Program to perform insertion sort.
Algorithm:
1. Create a function named insertionsort
2. Initialise currentvalue=alist[index] and position=index
3. while position>0 and alist[position-1]>currentvalue, perform the
following till len(alist)
4.alist[position]=alist[position-1]
5. position =position-1
6. alist[position]=currentvalue
7. Print the sortedlist
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 = []
n=int(input("enter the upper limit"))
print("enter",n,"numbers")
for i in range(0,n):
x=int(input())
alist.append(x)
insertionSort(alist)
print("The Sorted list are")
print(alist)
Sample Output:
enter the upper limit10
enter 10 numbers
34
26
10
32
78
91
105
36
59
47
The Sorted list are
[10, 26, 32, 34, 36, 47, 59, 78, 91, 105]
Result:
Thus the Python program to perform insertion sort is successfully
execute and the output is verified
5: Merge sort, Quick Sort
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
Defining a List in Python is easy. You just need to provide name of the list and initialize it with
values. Following is an example of a List in Python :
>>> myList
So you can see that a list named ‘myList’ was created with some elements.
Lists in python are zero indexed. This means, you can access individual elements in a list just as
you would do in an array. Here is an example :
>>> myList[0]
'The'
>>> myList[4]
'sun'
Lists cannot be accessed beyond the rightmost index boundary. Here is an example :
One can use the method insert, append and extend to add elements to a List.
The insert method expects an index and the value to be inserted. Here is an example of insert :
>>> myList.insert(0,"Yes")
>>> myList
So we see the value ‘yes’ was inserted at the index 0 in the list and all the other elements were
shifted accordingly.
The append method can take one or more elements as input and appends them into the list.
Here is an example :
>>> myList
So, the two values were appended towards the end of the list. Note that whether we add one
element or multiple elements to the list, if we have used append then they will be added as a
single element only. This can be proven if we try to check the length of myList now :
>>> len(myList)
So we see that though we added two elements but they are counted as a single element (or a
sub-list) in myList.
The other method that can be used to add elements to list is extend. Like append, it also expects
one or more values as input. But, unlike append, all the elements are added as individual
elements. Here is an example :
>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> len(myList)
10
So we see that each element got added as a separate element towards the end of the list.
3. Slice Elements from a List
Python also allows slicing of the lists. You can access a part of complete list by using index range.
There are various ways through which this can be done. Here are some examples :
If it is required to access a sub-list from index 1 to index 3 then it can be done in following way:
>>> myList[1:4]
Note that the index 4 was passed instead of 3 because if we pass index range x:y then values up
to index y-1 are printed.
Now, if it is required to access first ‘n’ elements of the list, then there is no need to provide
index ‘0’, only the value of ‘n’ is required. Here is an example :
>>> myList[:4]
Similarly, if last ‘n’ elements are required to be accessed then only starting index is required.
Here is an example :
>>> myList[4:]
So we see that all the elements beginning from index 4 till end of the list were displayed.
If neither starting index, nor the ending index is provided then complete list is displayed. Here is
an example :
>>> myList[:]
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
Lists can easily be searched for values using the index method that expects a value that is to be
searched. The output is the index at which the value is kept.
Here is an example :
>>> myList.index("revolves")
If it is desired to just whether an element is present in a list, it can be done in following way :
True
So we see that ‘True’ was returned as ‘sun’ was present in the list.
Python provides the remove method through which we can delete elements from a list. It
expects the value which is required to be deleted.
>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> myList.remove("Yes")
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> myList.remove("statement")
>>> myList
Here we see that remove can be used to easily delete elements in list. Here is how a sub list can
be deleted :
>>> myList
So we see that the sub list was deleted from the original list.
If it is required to access the last element and then to delete it, this can be done through pop
method.
>>> myList.pop()
'sure'
>>> myList
Python allows to use mathematical operators like +, * etc to be used with lists.
>>> myList
>>> myList
>>> myList
>>> myList *= 2
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.', 'The', 'earth', 'revolves', 'around', 'sun',
'for', 'sure', '.']
So we see that through + operator elements could be added to the list and through * operator
we can add the complete list repeatedly towards the end.
# initializing list
lis = [2, 1, 3, 5, 4, 3, 8]
# deletes 3,5,4
del lis[2 : 5]
print("\r")
# deletes 3
lis.pop(2)
Output:
3. insert(a, x) :- This function inserts an element at the position mentioned in its arguments. It
takes 2 arguments, position and element to be added at respective position.
4. remove() :- This function is used to delete the first occurrence of number mentioned in its
arguments.
filter_none
edit
play_arrow
brightness_4
# initializing list
lis = [2, 1, 3, 5, 3, 8]
print("\r")
# removes 3 at pos 2
lis.remove(3)
Output:
filter_none
edit
play_arrow
brightness_4
# initializing list
lis = [2, 1, 3, 5, 3, 8]
lis.sort()
print("\r")
lis.reverse()
Output:
7. extend(b) :- This function is used to extend the list with the elements present in another list.
This function takes another list as its argument.
8. clear() :- This function is used to erase all the elements of list. After this operation, list
becomes empty.
filter_none
edit
play_arrow
brightness_4
# initializing list 1
lis1 = [2, 1, 3, 5]
# initializing list 1
lis2 = [6, 4, 3]
lis1.extend(lis2)
# displaying list after sorting
print ("\r")
lis1.clear()
Output:
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
Example
Create a Tuple:
print(thistuple)
You can access tuple items by referring to the index number, inside square brackets:
Example
print(thistuple[1])
You can loop through the tuple items by using a for loop.
Example
for x in thistuple:
print(x)
if "apple" in thistuple:
Tuple Length
To determine how many items a tuple has, use the len() method:
Example
print(len(thistuple))
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
print(thistuple)
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
Example
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
Example
print(thistuple)
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position of where it was found
Source code:
PROGRAM-1 Date:
Aim: A) Create a list and perform the following methods 1) insert() 2) remove() 3) append() 4) len() 5)
pop() 6) clear()
Program:
a=[1,3,5,6,7,[3,4,5],"hello"]
print(a)
a.insert(3,20)
print(a)
a.remove(7)
print(a)
a.append("hi")
print(a)
len(a)
print(a)
a.pop()
print(a)
a.pop(6)
print(a)
a.clear()
print(a)
Output:
Exercise Questions:
2) access items
3) use get()
4)change values
5) use len()
1) Add items
2) len()
4)Access iems
Viva Questions:
1. Define list?