0% found this document useful (0 votes)
53 views58 pages

DSD LAB Manual Ex1-8 To Print

Uploaded by

s.shanmugapriya
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)
53 views58 pages

DSD LAB Manual Ex1-8 To Print

Uploaded by

s.shanmugapriya
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/ 58

Ex.No.

1A IMPLEMENTATION OF SIMPLE ABSTRACT CLASS IN

PYTHON

Aim:

To Write a python program to calculate electricity bill for a given tariff.

 1 to 100 units ------------- Rs10


 100 to 200 units------------Rs15
 200 to 300 units-------------Rs 20
 Above 300 units-------------Rs 25

Algorithm:

1. Declare a unit variable as input and pass the variable through the function
calculate bill.
2. The function calculate bill to contain the calculation as per the units
mentioned as Rs 10 for units between 1-100 and Rs 15 for units between
100-200 units and Rs20 for units between 200-300 units and for above
300 units amount is Rs25.
3. Get the input from the user as units for calculating the
electricity bill.
4. Display the amount to pay for the electricity bill as per the units
calculated for the particular month.
Program:

def calculateBill(units):

if(units <=100):

return units*10;

elif(units<=200):

return ((100*10)+(units-100)*15);

elif(units<=300):

return((100*10)+(100*15)+(units-200)*20);

elif(units>300):

return((100*10)+(100*15)+(100*20)+(units-300)*25):

#Driver Code

units=int(input(“Enter number of units:”)

print(“Payable Amount is:”)

print(calculateBill(units)):

OUTPUT:

Enter the number of units: 320

Payable Amount is:

5000
Ex.No.1B IMPLEMENTATION OF SIMPLE ABSTRACT CLASS IN

PYTHON

Aim:

To Write a Python Program for basic operations of calculator.

Algorithm:

1. Declare the first number as variable for getting the first value.
2. Declare the second number as another variable for getting the second
value.
3. Define the function CAL includes the different arithmetic operation as to
use the basic calculation of calculator as addition, multiplication, division
and subtraction.
4. Using the menu option in the while function to get the choice from the
user in order to make different calculation.
5. Using the break statement in each case to get the particular function from
the menu.
6. Display the results for each arithmetic operations.
Program:

Class cal()

def __init__(self a,b):

self.a=a

self.b=b

def add(self):

return self.a+self.b

def mul(self):

return self.a *self.b

def div(self):

return self.a/self.b

def sub(self):

return self.a-self.b

a=int(input(“Enter first number:”))

b=int(input(“Enter second number:”))

obj=cal(a,b)

choice=1

while choice!=0:

print(“0.Exit”)

print(“1.Add”)

print(“2.Subtraction”)

print(“3.Multiplication”)

print(“4.Division”)
choice=int(input(“Enter choice:”))

if choice==1:

print(“Result:”,obj.add())

elif choice==2:

print(“Result:”,obj.sub())

elif choice==3:

print(“Result:”,obj.mul())

elif choice==4:

print(“Result: “, round(obj.div(),2))

elif choice==0:

print(“Exiting:”)

else:

print(“Invalid choice!”)

print()

OUTPUT:

Enter first number: 25

Enter Second number: 5

0.Exit

1.Add

2.Subtraction

3.Mutliplication

4.Division
Enter choice:4

Result: 5.0

0.Exit

1.Add

2.Subtraction

3.Mutliplication

4.Division

Enter choice:0
Ex.No.2A IMPLEMENTATION OF SIMPLE RECURSIVE

ALGORITHMS IN PYTHON

Aim:

To write a Python Program to find factorial calculation using recursion.

Algorithm:

1. Define function factorial() to calculate factorial


2. Check if the entered number is 1 or 0, if true return the number
3. If false, call the function recursively to calculate factorial of the number
minus 1
4. Return the value of the number multiplied by the factorial of the number
minus 1
5. Print the result
Program:

def factorial(x):

if x==1:

return 1

else:

return(x*factorial(x-1))

num= int (input(“Enter a number: “))

result=factorial(num)

print(“The factorial of”, num, “is”,result)

OUTPUT:

Enter a number : 6

The factorial of 6 is is 720.


Ex.No.2B Implement recursive algorithms in Python

Aim:

To Implement a recursive algorithms in Python using Fibonacci Series

Algorithm:

1:Input the 'n' value until which the Fibonacci series has to be generated
2:Initialize sum = 0, a = 0, b = 1 and count = 1 .

3:while (count <= n)

4.print sum

5.Increment the count variable

6:swap a and b

7:sum = a + b

8:while (count > n)

9:End the algorithm

10:Else

11:Repeat from steps 4 to 7


Program:

No = 10

num1, num2 = 0, 1

count = 0

if No <= 0:

print("Invalid Number")

elif No == 1:

print("Fibonacci sequence for limit of ",No,":")

print(num1)

else:

print("Fibonacci sequence:")

while count < No:

print(num1)

nth = num1 + num2

num1 = num2

num2 = nth

count += 1
Output:

Fibonacci sequence:

13

21

34
Ex.No.2C Implementation of Simple Recursive Algorithms in Python

Aim:

To write a Python Program for Tower of Hanoi using recursion.

Algorithm :

1. Creating a recursive function.


2. def tower_of_hanoi(disks, source, auxiliary, target):
3. if(disks == 1):
4. print('Move disk 1 from rod {} to rod {}.'.format(source, target))
5. return.
# function call itself.

6. tower_of_hanoi(disks - 1, source, target, auxiliary)


7. print(‘Move disk 1 from rod{} to rod {}.’,format(disks,source,target))
8. tower_of_hanoi(disks - 1, auxiliary ,source, target,)
9. Get the number of disks from the user.
10.Display the movement of the three DISKS A,B,C.
Program:
def tower_of_hanoi(disks, source, auxiliary,target):
if(disks==1):
print(‘Move disk 1 from rod{} to rod {}
.’,format(source,target))
return
tower_of_hanoi(disks-1, source,target,auxiliary)
print(‘Move disk 1 from rod{} to rod {}
.’,format(disks,source,target))
tower_of_hanoi(disks-1,auxiliary, , source,target,)

OUTPUT:
Enter the number of disks: 3

Move disk 1 from rod A to rod C.

Move disk 2 from rod A to rod B.

Move disk 1 from rod C to rod B.

Move disk 3 from rod A to rod C.

Move disk 1 from rod B to rod A.

Move disk 2 from rod B to rod C.

Move disk 1 from rod A to rod C.


Ex.No.3A Implementation of List using Arrays in Python

Aim:

To write a Python Program to search element in list using arrays.

Algorithm:

1. Create a list using an array.


2. Define the function Search by Index and Search by Value.
3. In the function Search by Index ,to search an element in a list by specifying
its position.
4. In the function Search by Value,to search an element in a list by specifying
its value.
5. Display the result either by the Index or by the value .
Program:

Def SearchByIndex(array_val,index_val):

Item_index=index_val

n=len(array_val)

search_index=0

search_value=’undefined’

while(search_index<n)

if(search_index==item_index):

search_value=array_val[search_index]

break:

search_index= search_index+1:

return search_index:

Def SearchByValue(array_val,item):

n=len(array_val)

search_value=item

search_index=0

search_index=’undefined’

while(array_index<n):

if(array_val[array_index]==search_value):

search_index=array_ index

break:

array_index= array_index+1:

return search_value:
print(“////////////////SearchByIndex in an Array/////////////////”)

number_array=[4,5,2,7,9,13];

print(“________ Original Array___________________”)

for index,item in enumerate(number_array):

print(“Array “[“,index , ‘]’,item)

print(“Array Item “,item,” is the position “, searchByValue(number_array,13))

SearchByValue(number_array,9)

Print(“/////////////////////////////searchByValue in an Array////////////////////”)

String_array =[“start”,”to”,”study”, “from”,”basics”];

Print(“----------------------------Original Array-----------------------------“)

for idex,item in enumerate(string_array);

print(“Array[“,idex, “]”,item)

print(“Array Item “, item, “is in the

position”,searchByValue(string_arrray,”basics”)) # search by index

OUTPUT:

//////////////////////////searchByIndex in an Array///////////////////////////////////////

--------------------------Original Array-----------------------------------------

Array[0] 4

Array[1] 5

Array[2] 2

Array[3] 7

Array[4] 9
Array[5] 13

Array item ‘13’ is in the position 5

//////////////////////////searchByValue in an Array///////////////////////////////////////

--------------------------Original Array-----------------------------------------

Array[0] start

Array[1] to

Array[2] study

Array[3] from

Array[4] basics

Array item ‘basics’ is in the position 4


Ex.No:3A Implement List ADT using Python arrays

Aim:

To Implement List ADT using Python arrays

Algorithm

1.Using define function intialise the list

2.while loop to declare the elements until the condition is satisfied.

3.using convertarr function to convert the elemnts to an array

4.Stop the program


Program:

class node:

def __init__(self, data):

self.data=data

self.next=None

def add(data):

nn=node(0)

nn.data=data

nn.next=None

return nn

def printarray(a,n):

i=0

while(i<n):

print(a[i], end = " ")

i=i+1

def findlength(head):

cur=head

count=0

while(cur!=None):

count=count+1

cur=cur.next

return count

def convertarr(head):
len=findlength(head)

arr=[]

index=0

cur=head

while(cur!=None):

arr.append(cur.data)

cur=cur.next

printarray(arr, len)

head=node(0)

head=add(6)

head.next = add(4)

head.next.next = add(3)

head.next.next.next = add(4)

convertarr(head)

Output:

[6,4,3,4]

[6 4 3 4]
Ex.No:4 Implementation of Linked List in Python

Aim:

To write a Python Program to create linked list with n elements.

Algorithm:

1. Create a node and initialize with data and the next pointer.
2. Set the nodes as linked list by assign the head value as None and last node
as null.
3. Insert the data in the node by using append function if it is the new node set
as head,otherwise make it as next node.
4. Display the data in the linked node representation.
Program:

Class Node:

def __init__(self,data):

self.data=data

self.next=None

class LinkedList:

def __init__(self):

self.head=None

self.last_node=None

def append(self,data):

if self.last_node is None:

self.head=Node(data)

self.last_node=self.head

else:

self.last_node.next=Node(data)

self.last_node=self.last_node.next

def display(self):

current = self. Head

while current is not None:

print(current.data,end= “ “)

current =current.next

a_llist=LinkedList()

n=int(input(‘How many elements would you like to add?’))


for i in range(n):

data=int(input(‘Enter data item:’))

a_llist.append(data(

print(‘The linked list: ‘, end = “ “)

a_llist.display()

OUTPUT:

How many elements would you like to add? 5

Enter data item: 10

Enter data item: 20

Enter data item: 30

Enter data item : 40

Enter data item: 50

The Linked List : 10 20 30 40 50


Ex.No:4A Implementation of Linked List in Python

Aim:

To write a Python Program to search key element in a linked list.

Algorithm:

1. Create a node and initialize it with data and the next pointer.
2. Set as the node as linked list by initializing with head as Null.
3. Define the function “Push” to insert the element in the node.
4. Define the function “Search” to find the given element present in the
linked node or not found.
5. If the element present , display “YES” or if the element not present
display as “NO.
Program:

Class Node:

def __ init __(self,data):

self.data=data

self.next=None

Class LinkedList:

def __init __(self):

self.head=None

def push(self,new_data):

new_node=Node(new_data)

new_node.next=self.head

self.head=new_node

def search(self,x):

current=self.head

while current!= None:

if current .data==x:

return True

current=current.next

return False

if__name __ == ‘__ main __’:

llist = LinkedList()

#Use Push() to construct list

# 14-> 21->11->30->10
llist.push(10);

llist.push(30);

llist.push(11);

llist.push(21);

llist.push(14);

if llist.search(21):

print(“Yes”)

else:

print(“No”)

OUTPUT:

Enter element to search :21

Yes.
Ex.No:5A Implementation of Stack in Python

Aim:

To write a Python Program to insert elements into stack.

Algorithm:

1. Create the stack and initialize it with as list.


2. Define the function “push” to insert the value in the stack.
3. Define the function “Pop” to remove the value from the stack.
4. Define the function “check empty” to return the length of the
elements in the stack.
5. Display the elements from the stack after insertion and deletion into
the stack.
Program:

def create_stack():

stack=[]

return stack

def check_empty(stack):

return len(stack)==0

def push(stack,item):

stack.append(item)

print(“pushed item:” + item)

def pop(stack):

if (check_empty(stack)):

return “stack is empty”

return stack.pop()

stack=create_stack()

push(stack,str(1))

push(stack,str(2))

push(stack,str(3))

push(stack,str(4))

print(“popped item: “ + pop(stack))

print(“stack after popping an element: “ = str(stack))


OUTPUT:

Pushed item :1

Pushed item :2

Pushed item :3

Pushed item :4

Popped item :4

Stack after popping an element : [‘1’,’2’,’3’]


Ex:NO:5b Implementation of Queue in Python

Aim:

TO Write a python program to implement queue

Algorithm:

1. Create a Class Queue to include Enqueue,Dequeue and Size and


display function along with the initialization.
2. In Enqueue function, insert the elements into the queue at the end of
the list.
3. In Dequeue function, remove the element from the front position of
the list
4. In size function ,to display the number of elements in the Queue.
5. In Display function, print the number of elements in the Queue.
6. To initialize the value in the Initialization method.
7. Create an Object to call the Enqueue and Dequeue methods.
Program:

class Queue:

def __init__(self):

self.queue=[]

def enqueue(self,item):

self.queue.append(item)

def dequeue(self):

if len(self.queue)<1:

return None

return self.queue.pop(0)

def display(self):

print(self.queue)

def size(self):

return len(self.queue)

q=Queue()

q.enqueue(1)

q.enqueue(2)

q.enqueue(3)

q.enqueue(4)

q.enqueue(5)

q.display()

q.dequeue()

print("After removing an element")


q.display()

OUTPUT:

[1,2,3,4,5]

After removing an element:

[2.3.4.5]

.
Ex.No:6A Application of List ADT in Python

Card Game

Aim:

To write a Python Program for card of game in Python in List ADT.

Algorithm:

1. Create a class Card, a class Player, and a class Deck.


2. The card class will contain a value self and suit
3. Create the attributes suit.
4. Set this value to whatever is sent while making a card.
5. Create a new method for displaying the card.
6. Make a string that will print out the suit and value in the show
method.
7. In the Deck class, Start by making a 52-card deck including four suits
ranging from Ace to King.
8. Let begin with an init method that creates a cards attribute with just an
empty array that we will add to and a construction method to generate
our deck
9. Inside the Deck class a build method that includes in self, and alsot to
make 52 cards with four suits.
10.In the for loop, which loops via “suit.”and proceed inside the 1st
loop, we construct a second for loop that loops through values ranging
(1,14).
11.Use the Fisher-Yates shuffle by importing random
12.Design a method for shuffling the cards. A loop will be created, which
will help us to go from the end of the beginning of the list.
13.Make a class to set name and empty list with a name attribute and
hand attribute, respectively.
14.Get the two players name and display the match result as which one
person win or tie in the match accordingly.
Program:

from random import shuffle

class Card:

suits = ["spades",

"hearts",

"diamonds",

"clubs"]

values = [None, None,"2", "3",

"4", "5", "6", "7",

"8", "9", "10",

"Jack", "Queen",

"King", "Ace"]

def __init__(self, v, s):

"""suit + value are ints"""

self.value = v

self.suit = s

def __lt__(self, c2):

if self.value < c2.value:

return True

if self.value == c2.value:

if self.suit < c2.suit:

return True

else:
return False

return False

def __gt__(self, c2):

if self.value > c2.value:

return True

if self.value == c2.value:

if self.suit > c2.suit:

return True

else:

return False

return False

def __repr__(self):

v = self.values[self.value] +\

" of " + \

self.suits[self.suit]

return v

class Deck:

def __init__(self):

self.cards = []

for i in range(2, 15):

for j in range(4):

self.cards\

.append(Card(i,
j))

shuffle(self.cards)

def rm_card(self):

if len(self.cards) == 0:

return

return self.cards.pop()

class Player:

def __init__(self, name):

self.wins = 0

self.card = None

self.name = name

class Game:

def __init__(self):

name1 = input("p1 name ")

name2 = input("p2 name ")

self.deck = Deck()

self.p1 = Player(name1)

self.p2 = Player(name2)

def wins(self, winner):

w = "{} wins this round"

w = w.format(winner)

print(w)
def draw(self, p1n, p1c, p2n, p2c):

d = "{} drew {} {} drew {}"

d = d.format(p1n,

p1c,

p2n,

p2c)

print(d)

def play_game(self):

cards = self.deck.cards

print("beginning War!")

while len(cards) >= 2:

m = "q to quit. Any " + \

"key to play:"

response = input(m)

if response == 'q':

break

p1c = self.deck.rm_card()

p2c = self.deck.rm_card()

p1n = self.p1.name

p2n = self.p2.name

self.draw(p1n,

p1c,
p2n,

p2c)

if p1c > p2c:

self.p1.wins += 1

self.wins(self.p1.name)

else:

self.p2.wins += 1

self.wins(self.p2.name)

win = self.winner(self.p1,

self.p2)

print("War is over.{} wins"

.format(win))

def winner(self, p1, p2):

if p1.wins > p2.wins:

return p1.name

if p1.wins < p2.wins:

return p2.name

return "It was a tie!"

game = Game()

game.play_game()
Output:

P1 name : Ramu

P2 name: Jeron

Beginning War!

Q to quit.any key to play: d

Ramu drew 10 of spades Jeron drew Ace of hearts

Jeron wins this round

Q to quit. Any key to play:7

Ramu drew 4 of diamonds Jeron drew 9 of clubs

Jeron wins this round

Q to quit.any key to play.q


Ex.No:6B Application of STACK ADT in Python

Infix to Postfix conversion

Aim:

To write a Python Program for infix to postfix conversion using stack


implementation.

Algorithm:

1. Create a set contains the operators which includes addition,


subtraction,multiplication and division and parenthesis and Exponential
power.
2. Set the Priority for each of the operators as +:1,-:1,*:2,/:2,^;3
3. Define the function “infix to postfix conversion” where the input as operand
entered into output array.
4. Otherwise put the operators based on the higher precedence the operators are
pushed or it can be removed from the stack.
5. If the operand ‘(‘ as opening parenthesis does not consider its precedence
and pushed every operator within it into the stack.
6. When ‘)’ closing parenthesis matches the operators inside the paranthesis
are removed and put it into the output array.
7. Get the input as “Infix Expression” from the user and Pass it to the
function“infix to postfix conversion” as parameter.
8. Display the output as ‘Postfix Expression”.
Program:

operators=set([‘+’,’-‘,’*’,’/’,’(‘,’)’,’^’]) # Collection of operators

priority={‘+’:1,’-‘:1,’*’:2,’/’:2,’^’:3} # dictionary having priorities of operators

def infixToPostfix(expression):

stack=[] # initialization of empty stack

output=” “

for character un expression:

if character not in operators”

# if an operand append in postfix expression

Output+ = character

elif character ==’(‘: # else operators push onto stack

stack.append(‘(‘)

elif character==’)’:

while stack and stack [-1]! =’(‘:

output+= stack.pop()

stack.pop()

else:

while stack and stack [-1]!=’(‘ and priority [character]<=priority[stack [-1]]:

output+= stack.pop()

stack.append(character)

while stack:

output+= stack.pop()

return output
expression=input(‘Enter infix expression’)

print(‘infix notation: ‘, expression)

print(‘postfix notation:’, infixToPostfix(expression))

Output:

Enter unfix expression : a+b *c^d-e^f+g*h-i

Infix notation: a+b*c^d-e^f+g*h-i

Postfix notation: abcd^*+ef^-gh*+i-


Ex.No:6C Application of QUEUE ADT in Python

First come first serve scheduling

Aim:

To write a Python Program for first come first serve scheduling program.

Algorithm:

1. Enter the number of processes for scheduling.


2. Enter the Arrival time for each process
3. Enter the Burst time for each process.
4. For each process, calculate the Waiting time, Exit time and Turnaround
Time.
5. Display the wait time, exit time and turnaround time
Program:

Print(“FIRST COME FIRST SERVE SCHEDULING”)

n=int(input(“Enter the number of processes:”))

d=dict()

for i in range(n):

key=”P” +str(i+1)

a= int(input(“Enter the arrival time of proces:”+str(i+1)+”:”))

b= int(input(“Enter the burst time of proces:”+str(i+1)+”:”))

l=[]

l.append(a)

l.append(b)

d[key]=1

d=sorted(d.items(), key=lambda item: item[1][0])

ET=[]

for i in range(len(d)):

#first process

if(i==0):

ET.append(d[i][1][1])

#get prevET +newBT

else:

ET.append(ET[i-1]+d[i][1][1])

TAT= []

for i in range(len(d)):
TAT.append(ET[i]-d[i][1][0])

WT=[]

for i in range(len(d)):

WT.append(TAT[i]-d[i][1][1])

avg_WT=0

for i in WT:

avg_WT +=i

avg_WT= (avg_WT/n)

print(“Process | Arrival | Burst | Exit | TurnAround | Wait |”)

for i in range(n):

print(“ “,d[i][0], “ | “ d[i][1][0], “ | “,d[i][1][1], “ | “,ET[i],” |


“ ,TAT[i], “ | “, WT[i], “ | “)

print(“Average Waiting Time:”, avg_WT)

OUTPUT:

FIRST COME FIRST SERVE SCHEDULING:

Enter number of processes:4

Enter arrival time of process1:5

Enter burst time of process1:2

Enter arrival time of process24

Enter burst time of process2:3


Enter arrival time of process3:3

Enter burst time of process3:1

Enter arrival time of process4:3

Enter burst time of process4:2

Process | Arrival | Burst | Exit | TurnAround | Wait

P3 3 1 1 -2 -3

P4 3 2 3 0 -2

P2 4 3 6 2 -1

P1 5 2 8 3 1

Average Waiting Time : -1.25

Ex.No:7A Implementation of Linear Searching Techniques


Aim:

To write a Python script for implementing linear search technique.

Algorithm:

1. Create a list containing the n number of elements in it.


2. Define the function linear _search in order to find the given element present
in the list or not present in the list.
3. Get the element to be searched from the user as input.
4. Searching the element as matching the key value present in the list.
5. Display the result as the element found at the position ,otherwise ,display
that the element is not found.

Program:
def linear_search(list1,n,key):

#Searching list1 sequentially.

for i in range(0,n):

if(list[i]==key):

return i

return -1

list1 = [1,3,5,4,7,9]

print(list1)

key=int(input(“Enter the key to search:”))

n=len(list1)

res=linear_search(list1,n,key)

if(res==-1):

print(“Element not found”)

else:

print(“Element found at index:”,res)

OUTPUT:

[1,3,5,4,7,9]

Enter the key to search :5

Element found at index: 2

Enter the key to search: 10

Element not found.

Ex.No:7B Implementation of Binary Searching Techniques


Aim:

To write a Python Program to search an element in a given linear list using


recursion.

Algorithm:

1. Create a sorted list with group of characters


2. Define the function “binarysearcharr” , find the mid value and check the
element is either in the lower portion or in the higher portion with the mid
value.
3. If the element is present, display the element is found at the position.
4. If the element is not present, display that the element is not found.

Program:
def binarySeachAppr(arr,start,end,x):

if end>=start:

mid=start+(end-start)//2

if arr[mid]==x:

return mid

elif arr[mid] > x:

return binarySeachAppr(arr, start, mid-1, x)

else:

return binarySearchAppr(arr,mid+1,end,x)

else:

return -1

arr= sorted([‘t’,’u’,’t’,’o’,’r’,’i’,’a’,’l’])

x=’r’

result= binarySearchAppr(arr,0, len(arr)-1,x)

if result!=-1:

print(“Element is present at index:”, str(result))

else:

print(“Element is not present in array:”)

OUTPUT:

Element is present at index :4

Ex.No:7C Implementation of Sorting Algorithm


Aim:

To Implement sorting Algorithm using Quick Sort and Insertion Sort algorithm
using python

Algorithm:

Quick Sort:

1. Find a “pivot” item in the array. This item is the basis for comparison for a
single round.

2. Start a pointer (the left pointer) at the first item in the array.

3. Start a pointer (the right pointer) at the last item in the array.

4. While the value at the left pointer in the array is less than the pivot value, move
the left pointer to the right (add 1). Continue until the value at the left pointer is
greater than or equal to the pivot value.

5. While the value at the right pointer in the array is greater than the pivot value,
move the right pointer to the left (subtract 1). Continue until the value at the right
pointer is less than or equal to the pivot value.

6. If the left pointer is less than or equal to the right pointer, then swap the values
at these locations in the array.

7. Move the left pointer to the right by one and the right pointer to the left by one.

Insertion Sort:

1. Compare each element with preceding elements

2. Shift each compared element on the right

3. Place the element at the empty spot

4. Print the sorted array


Program( Quick Sort):

def partition(arr,low,high):

i = ( low-1 )

pivot = arr[high]

for j in range(low , high):

if arr[j] <= pivot:

i = i+1

arr[i],arr[j] = arr[j],arr[i]

arr[i+1],arr[high] = arr[high],arr[i+1]

return ( i+1 )

def quickSort(arr,low,high):

if low < high:

pi = partition(arr,low,high)

quickSort(arr, low, pi-1)

quickSort(arr, pi+1, high)

arr = [2,5,3,8,6,5,4,7]

n = len(arr)

quickSort(arr,0,n-1)

print ("Sorted array is:")

for i in range(n):

print (arr[i],end=" ")

Program( Insertion Sort):


def insertionSort(arr):

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

key = arr[i]

j = i-1

while j >=0 and key < arr[j] :

arr[j+1] = arr[j]

j -= 1

arr[j+1] = key

arr = ['t','u','t','o','r','i','a','l']

insertionSort(arr)

print ("The sorted array is:")

for i in range(len(arr)):

print (arr[i])

Output:

Quick Sorted array is:

23455678

Insertion sorted array is:

t
t

Ex.No:8 Implementation of Hash tables


Aim:

To Implement the Hash tables using python

Algorithm:

1.Create a structure, data (hash table item) with key and value as data.

2.for loops to define the range within the set of elements.

3.hashfunction(key) for the size of capacity

4.Using insert(),removal() data to be presented or removed.

5. Stop the program

Program:
hashTable = [[],] * 10

def checkPrime(n):

if n == 1 or n == 0:

return 0

for i in range(2, n//2):

if n % i == 0:

return 0

return 1

def getPrime(n):

if n % 2 == 0:

n=n+1

while not checkPrime(n):

n += 2

return n

def hashFunction(key):

capacity = getPrime(10)

return key % capacity

def insertData(key, data):

index = hashFunction(key)

hashTable[index] = [key, data]

def removeData(key):

index = hashFunction(key)

hashTable[index] = 0
insertData(123, "apple")

insertData(432, "mango")

insertData(213, "banana")

insertData(654, "guava")

print(hashTable)

removeData(123)

print(hashTable)

Output:

[[], [], [123, 'apple'], [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]

[[], [], 0, [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]

You might also like