0% found this document useful (0 votes)
14 views18 pages

DSPLAb

The document contains multiple Python programs demonstrating various data structures and algorithms, including lists, dictionaries, tuples, sets, Fibonacci sequence, factorial calculation, binary and linear search, insertion sort, stack and queue implementations, Towers of Hanoi, and linked list traversal. Each program includes an algorithm, code implementation, and sample output. The programs illustrate fundamental programming concepts and data structure operations in Python.

Uploaded by

yuvarajbahubali1
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)
14 views18 pages

DSPLAb

The document contains multiple Python programs demonstrating various data structures and algorithms, including lists, dictionaries, tuples, sets, Fibonacci sequence, factorial calculation, binary and linear search, insertion sort, stack and queue implementations, Towers of Hanoi, and linked list traversal. Each program includes an algorithm, code implementation, and sample output. The programs illustrate fundamental programming concepts and data structure operations in Python.

Uploaded by

yuvarajbahubali1
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/ 18

1.

Python program to Use and demonstrate basic data structures


Algorithm:

Step1: Declare & Initialise the values of List

l1 = [1, 2,"ABC", 3, "xyz", 2.3]

print(l1)

Step 2: Declare & Initialise the values of Dictionary

d1={"a":134,"b":266,"c":343}

print(d1)

Step 3: Declare & Initialise the values of Tuples

t1=(10,20,30,40,50,40)

print (t1)

Step 4: Declare & Initialise the values of Sets

s1={10,30,20,40}

print(s1)

Program:

print("List")

l1 = [1, 2,"ABC", 3, "xyz", 2.3]

print(l1)

print("Dictionary")

d1={"a":134,"b":266,"c":343}

print(d1)

print("Tuples")

t1=(10,20,30,40,50,40)

print (t1)

print("Sets")

s1={10,30,20,40}

print(s1)
Output:

List

[1, 2, 'ABC', 3, 'xyz', 2.3]

Dictionary

{'a': 134, 'c': 343, 'b': 266}

Tuples

(10, 20, 30, 40, 50, 40)

Sets

set([40, 10, 20, 30])


2.Python program to Implement Fibonacci sequence with dynamic
programming.

Algorithm:

Step1. Read number of terms n.

Step2. Send n to recursive method recur_fibo()

Step3. if n <= 1 then return n

Step4. otherwise return(recur_fibo(n-1) + recur_fibo(n-2))

Program:

def fib(n):

if n<=1:

return n

f = [0,1]

for i in range(2,n+1):

f.append(f[i-1]+f[i-2])

print("The Fibonacci sequence is:",f)

return f[n]

n = int(input("Enter the term:"))

print("The Fibonacci value is:",fib(n))

Output:-

Enter the term:3

The Fibonacci sequence is: [0, 1, 1, 2]

The Fibonacci value is: 2


3.Python Program to Find Factorial of a Given Number Using Recursive
Function
Algorithm:

Step1: if n == 1 then return 1

Step2: else

f=return(n*fact(n-1))

Step3: return f

Program:

def fact(n):

if n == 1:

return 1

else:

return(n*fact(n-1))

n=int(input("Enter the number:"))

print("The factorial of number is:",fact(n))

Output:

Enter the number:3

The factorial of number is: 6


4.Python Program To Implement binary search and compute space and time
complexities & plot graph using asymptotic notations

Algorithm:

Step1: Given a sorted list of a[] of n elements, search a given element x in list.

Step2: Search a sorted list by repeatedly dividing the search interval in half. Begin with an
interval

covering the whole list.

Step3: If the search key is less than the item in the middle item, then narrow the interval to the

lower half. Otherwise narrow it to the upper half.

Step4: Repeat the procedure until the value is found or the interval is empty

Program:

import time

def binarysearch(a,key):

low = 0

high= len(a)-1

while low <=high:

mid = (high+low)//2

if a[mid] == key:

return mid

elif key <a[mid]:

high = mid - 1

else:

low = mid + 1

return - 1

start = time.time()

a = [13,24,35,46,57,68,79]

print("the array elements are:",a)


k = int(input("enter the key element to search:"))

r = binarysearch(a,k)

if r == -1:

print("Search Unsuccessful")

else:

print("Search Successful key found at location:",r+1)

end = time.time()

print("Runtime of the program is:",end-start)

Output:-

'the array elements are:', [13, 24, 35, 46, 57, 68, 79])

enter the key element to search:46

'Search Successful key found at location:' 4

'Runtime of the program is:', 13.791000127792358


5.Python Program To Implement Linear search in python

Algorithm:

Step1: Given a list of n elements and search a given element x in the list using linear search.

Step2: Start from the leftmost element of list a[] and one by one compare x with each element of
list a[].

Step3: If x matches with an element, return the index.

Step4: If x doesn’t match with any of elements, return -1.

Program:

def linear_search(arr, n):

for i in range(len(arr)):

if arr[i] == n:

return i

return -1

arr = [3, 2, 6, 19, 15, 20]

n = 15

r = linear_search(arr, n)

if(r == -1):

print("Element not found")

else:

print("Element found at index",str(r))

Output:

'Element found at index', '4'


6.Write a python program to implement insertion sort

Algorithm:

Step1: Spilt a list in two parts - sorted and unsorted.

Step2: Iterate from arr[1] to arr[n] over the given array.

Step3: Compare the current element to the next element.

Step4: If the current element is smaller than the next element,

compare to the element before, Move to the greater elements one position up to make space for
the swapped element.

Program:

def insertion_sort(list1):

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

value = list1[i]

j=i-1

while j >= 0 and value < list1[j]:

list1[j + 1] = list1[j]

j -= 1

list1[j + 1] = value

return list1

list1 = [10, 5, 13, 8, 2]

print("The unsorted list is:", list1)

print("The sorted list1 is:", insertion_sort(list1))

Output:

'The unsorted list is:', [10, 5, 13, 8, 2]

'The sorted list1 is:', [2, 5, 8, 10, 13]


7. Write a python program Implement stack data structure.

Stack Operations:

push(value) - Inserting value into the stack

pop(value) - Delete a value from the Stack

display(value) - Displays the elements of a Stack

Exit-Terminatefrom the stack

Algorithm:

Step1: Stack is a linear data structure which works under the principle of last in first out. Basic
operations: push, pop, display.

Step2: PUSH: if (top==MAX), display Stack overflow.

Otherwise reading the data and making stack [top]

=data and incrementing the top value by doing top++.

Step3: Pop: if (top==0), display Stack underflow.

Otherwise printing the element at the top of the stack and decrementing the top value by doing
the top.

Step4: DISPLAY: If (top==0), display Stack is empty. Otherwise printing the elements in the
stack from stack

[0] to stack [top].

Program:

s = []

def push():

if len(s) == size:

print("Stack is Full")

else:

item = input("Enter the element:")


s.append(item)

def pop():

if(len(s) == 0):

print("Stack is Empty")

else:

item = s[-1]

del(s[-1])

print("The deleted element is:",item)

def display():

size = len(s)

if(size == 0):

print("Stack is Empty")

else:

for i in reversed(s):

print(i)

size = int(input("Enter the size of Stack:"))

while(True):

choice = int(input("1-push 2-POP 3-DISPLAY 4-EXIT Enter your choice:"))

if(choice == 1):

push()

elif(choice == 2):

pop()

elif(choice == 3):

display()

else:

break
Output:

Enter the size of Stack:4

1-push 2-POP 3-DISPLAY 4-EXIT Enter your choice:1

Enter the element:10

1-push 2-POP 3-DISPLAY 4-EXIT Enter your choice:1

Enter the element:20

1-push 2-POP 3-DISPLAY 4-EXIT Enter your choice:1

Enter the element:30

1-push 2-POP 3-DISPLAY 4-EXIT Enter your choice:1

Enter the element:40

1-push 2-POP 3-DISPLAY 4-EXIT Enter your choice:3

40

30

20

10

1-push 2-POP 3-DISPLAY 4-EXIT Enter your choice:2

('The deleted element is:', 40)


8. Python program to demonstrate queue implementation using list

Algorithm:

Step1: Initializing a queue

queue = []

Step2: Adding elements to the queue

queue.append('a')

queue.append('b')

queue.append('c')

Step3:Removing elements from the queue

print(queue.pop(0))

print(queue.pop(0))

print(queue.pop(0))

Step4: Display Elements From Queue after removing elements


Program:

# Initializing a queue

queue = []

# Adding elements to the queue

queue.append('a')

queue.append('b')

queue.append('c')

print("Initial queue")

print(queue)

# Removing elements from the queue

print("\nElements dequeued from queue")

print(queue.pop(0))

print(queue.pop(0))

print(queue.pop(0))

print("\nQueue after removing elements")

print(queue)

Output:

Initial queue

['a', 'b', 'c']

Elements dequeued from queue

Queue after removing elements

[]
9.Python Program To Implement solution for towers of Hanoi.
Rules for towers of Hanoi.

1.Only one disk can be moved at a time.

2.Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack

i.e. a disk can only be moved if it is the uppermost disk on a stack.

3.No disk may be placed on top of a smaller disk.

Algorithm:

Step 1 : Shift first disk from 'A' to 'C'.

Step 2 : Shift second disk from 'A' to 'B'.

Step 3 : Shift first disk from 'C' to 'B'.

Step 4 : Shift third disk from 'A' to 'C'.

Step 5 : Shift first disk from 'B' to 'A'.

Step 6 : Shift second disk from 'B' to 'C'.

Step 7 : Shift first disk from 'A' to 'C'.

Program:

def towerofhanoi(n,source,destination,auxiliary):

if n == 1:

print("Move disk 1 from source",source,"to destination",destination)

return

towerofhanoi(n-1,source,auxiliary,destination)

print("Move disk",n,"from source",source,"to destination",destination)

towerofhanoi(n-1,auxiliary,destination,source)

n=4

towerofhanoi(n,'A','B','C')
Output:-

Move disk 1 from source A to destination C

Move disk 2 from source A to destination B

Move disk 1 from source C to destination B

Move disk 3 from source A to destination C

Move disk 1 from source B to destination A

Move disk 2 from source B to destination C

Move disk 1 from source A to destination C

Move disk 4 from source A to destination B

Move disk 1 from source C to destination B

Move disk 2 from source C to destination A

Move disk 1 from source B to destination A

Move disk 3 from source C to destination B

Move disk 1 from source A to destination C


10.Write a python program for Traversing a Linked List
Algorithm:

Step1: If First=NULL then {print “List empty” STOP};

Step2: count=0;

Step3: ptr=First; {point ptr to the 1st node}

Step4: While ptr<> NULL repeat Steps 5 to 6

Step5: count=count+1;

Step6: ptr=NEXT(ptr) [shift ptr to the next node]

Step7: print (‘Number of nodes=’, count)

Step8: END
Program:

class Node:

def __init__(self, dataval=None):

self.dataval = dataval

self.nextval = None

class SLinkedList:

def __init__(self):

self.headval = None

def listprint(self):

printval = self.headval

while printval is not None:

print (printval.dataval)

printval = printval.nextval

list = SLinkedList()

list.headval = Node("Mon")

e2 = Node("Tue")

e3 = Node("Wed")

# Link first Node to second node

list.headval.nextval = e2

# Link second Node to third node

e2.nextval = e3

list.listprint()

Output:
Mon

Tue

Wed

You might also like