DSD LAB Manual Ex1-8 To Print
DSD LAB Manual Ex1-8 To Print
PYTHON
Aim:
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
print(calculateBill(units)):
OUTPUT:
5000
Ex.No.1B IMPLEMENTATION OF SIMPLE ABSTRACT CLASS IN
PYTHON
Aim:
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()
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
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:
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:
Algorithm:
def factorial(x):
if x==1:
return 1
else:
return(x*factorial(x-1))
result=factorial(num)
OUTPUT:
Enter a number : 6
Aim:
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 .
4.print sum
6:swap a and b
7:sum = a + b
10:Else
No = 10
num1, num2 = 0, 1
count = 0
if No <= 0:
print("Invalid Number")
elif No == 1:
print(num1)
else:
print("Fibonacci sequence:")
print(num1)
num1 = num2
num2 = nth
count += 1
Output:
Fibonacci sequence:
13
21
34
Ex.No.2C Implementation of Simple Recursive Algorithms in Python
Aim:
Algorithm :
OUTPUT:
Enter the number of disks: 3
Aim:
Algorithm:
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];
SearchByValue(number_array,9)
Print(“/////////////////////////////searchByValue in an Array////////////////////”)
Print(“----------------------------Original Array-----------------------------“)
print(“Array[“,idex, “]”,item)
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
//////////////////////////searchByValue in an Array///////////////////////////////////////
--------------------------Original Array-----------------------------------------
Array[0] start
Array[1] to
Array[2] study
Array[3] from
Array[4] basics
Aim:
Algorithm
class node:
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):
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:
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):
print(current.data,end= “ “)
current =current.next
a_llist=LinkedList()
a_llist.append(data(
a_llist.display()
OUTPUT:
Aim:
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:
self.data=data
self.next=None
Class LinkedList:
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
if current .data==x:
return True
current=current.next
return False
llist = LinkedList()
# 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:
Yes.
Ex.No:5A Implementation of Stack in Python
Aim:
Algorithm:
def create_stack():
stack=[]
return stack
def check_empty(stack):
return len(stack)==0
def push(stack,item):
stack.append(item)
def pop(stack):
if (check_empty(stack)):
return stack.pop()
stack=create_stack()
push(stack,str(1))
push(stack,str(2))
push(stack,str(3))
push(stack,str(4))
Pushed item :1
Pushed item :2
Pushed item :3
Pushed item :4
Popped item :4
Aim:
Algorithm:
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()
OUTPUT:
[1,2,3,4,5]
[2.3.4.5]
.
Ex.No:6A Application of List ADT in Python
Card Game
Aim:
Algorithm:
class Card:
suits = ["spades",
"hearts",
"diamonds",
"clubs"]
"Jack", "Queen",
"King", "Ace"]
self.value = v
self.suit = s
return True
if self.value == c2.value:
return True
else:
return False
return False
return True
if self.value == c2.value:
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 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:
self.wins = 0
self.card = None
self.name = name
class Game:
def __init__(self):
self.deck = Deck()
self.p1 = Player(name1)
self.p2 = Player(name2)
w = w.format(winner)
print(w)
def draw(self, p1n, p1c, p2n, p2c):
d = d.format(p1n,
p1c,
p2n,
p2c)
print(d)
def play_game(self):
cards = self.deck.cards
print("beginning War!")
"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)
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)
.format(win))
return p1.name
return p2.name
game = Game()
game.play_game()
Output:
P1 name : Ramu
P2 name: Jeron
Beginning War!
Aim:
Algorithm:
def infixToPostfix(expression):
output=” “
Output+ = character
stack.append(‘(‘)
elif character==’)’:
output+= stack.pop()
stack.pop()
else:
output+= stack.pop()
stack.append(character)
while stack:
output+= stack.pop()
return output
expression=input(‘Enter infix expression’)
Output:
Aim:
To write a Python Program for first come first serve scheduling program.
Algorithm:
d=dict()
for i in range(n):
key=”P” +str(i+1)
l=[]
l.append(a)
l.append(b)
d[key]=1
ET=[]
for i in range(len(d)):
#first process
if(i==0):
ET.append(d[i][1][1])
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)
for i in range(n):
OUTPUT:
P3 3 1 1 -2 -3
P4 3 2 3 0 -2
P2 4 3 6 2 -1
P1 5 2 8 3 1
Algorithm:
Program:
def linear_search(list1,n,key):
for i in range(0,n):
if(list[i]==key):
return i
return -1
list1 = [1,3,5,4,7,9]
print(list1)
n=len(list1)
res=linear_search(list1,n,key)
if(res==-1):
else:
OUTPUT:
[1,3,5,4,7,9]
Algorithm:
Program:
def binarySeachAppr(arr,start,end,x):
if end>=start:
mid=start+(end-start)//2
if arr[mid]==x:
return mid
else:
return binarySearchAppr(arr,mid+1,end,x)
else:
return -1
arr= sorted([‘t’,’u’,’t’,’o’,’r’,’i’,’a’,’l’])
x=’r’
if result!=-1:
else:
OUTPUT:
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:
def partition(arr,low,high):
i = ( low-1 )
pivot = arr[high]
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):
pi = partition(arr,low,high)
arr = [2,5,3,8,6,5,4,7]
n = len(arr)
quickSort(arr,0,n-1)
for i in range(n):
key = arr[i]
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
arr = ['t','u','t','o','r','i','a','l']
insertionSort(arr)
for i in range(len(arr)):
print (arr[i])
Output:
23455678
t
t
Algorithm:
1.Create a structure, data (hash table item) with key and value as data.
Program:
hashTable = [[],] * 10
def checkPrime(n):
if n == 1 or n == 0:
return 0
if n % i == 0:
return 0
return 1
def getPrime(n):
if n % 2 == 0:
n=n+1
n += 2
return n
def hashFunction(key):
capacity = getPrime(10)
index = hashFunction(key)
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'], [], [], [], []]