[go: up one dir, main page]

0% found this document useful (0 votes)
13 views15 pages

Record

The document provides a comprehensive overview of various data structures and algorithms implemented in Python, including lists, tuples, sets, dictionaries, and their operations. It demonstrates the implementation of linear search, sorting algorithms (bubble, selection, insertion), binary search trees, Fibonacci series, linked lists, stacks, queues, and hash functions. Additionally, it includes performance analysis through time complexity graphs using matplotlib.

Uploaded by

Mohammed Fahad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views15 pages

Record

The document provides a comprehensive overview of various data structures and algorithms implemented in Python, including lists, tuples, sets, dictionaries, and their operations. It demonstrates the implementation of linear search, sorting algorithms (bubble, selection, insertion), binary search trees, Fibonacci series, linked lists, stacks, queues, and hash functions. Additionally, it includes performance analysis through time complexity graphs using matplotlib.

Uploaded by

Mohammed Fahad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1) Write a python program to use and demonstrate basic data

structures.

lst=["Python","Java","HTML","CSS","Bootstrap","php"]
print(lst)

print(lst[0]) #Accessing a values of a list using an index number


print(lst[1:5])

lst[2]="Advance Java"
print(lst) #Updating a list using index number

del lst[2]
print(lst) #Deleting a list element using an index number

tup=("Python","Java","HTML","CSS","Bootstrap","php")
print(tup)
print(tup[0]) #Accessing a values of a tuple using an index number
print(tup[1:5])
tup1=("Advance Java","DS Python")
print(tup+tup1) #Updating a tuple by creating a new tuple

# del tup,tup1 # Deletion of a tuple using a del keyword


# print(tup1+tup)

lang={"Python","Java","HTML","CSS","Bootstrap","php"}
print(lang)

for x in lang: #Accessing a vlues of a set


print(x)

lang.add("Advance Java") #Adding items to a set


print(lang)

lang.discard("Advance Java")
print(lang) #Removing an element using discard method

lang1={"Advance Java","DS with python","HTML","php"}


print(lang|lang1) #Union of set

dict1={
"Name":"Python",
"year":1989,
"founder":"Guido van Rossum"
}
print(dict1)
print(dict1)
print(dict1["Name"]) #Accessing a values of dictionary using a key
pairs
print(dict1["year"])

dict1["type"]="object oriented programing language"


print(dict1["type"]) #Updating a dictionary by adding a new entry

del dict1["type"]
del dict1; #Deleting a whole dictionary using a del keyword
# print(dict1)

2) Give an example to show the implementation of an ADT with all it


operation

lst=["Python","Java","HTML","CSS","Bootstrap","php"]
print(lst)

print(lst[2])

lst.insert(3,"Advance Java")
print(lst)

lst.remove("Advance Java")
print(lst)

print(len(lst))

del lst
print(lst)
''' Implementation of stack on list'''
lst_mystack=[]

lst_mystack.append("Python")
lst_mystack.append("Java")
lst_mystack.append("HTML")
lst_mystack.append("CSS")

print(lst_mystack)

lst_mystack.pop()
lst_mystack.pop()
lst_mystack.pop()
lst_mystack.pop()

print(lst_mystack)

# Implmentation of queue using queue module


from queue import Queue
from resource import prlimit

q=Queue(maxsize=4)
print("Initial Size Before Insertion:",q.qsize())
q.put(1)
q.put(2)
q.put(3)
q.put(4)
print("After Insertion:",q.qsize())
print("Queue is Full or Not:",q.full())
print("Size of Queue:",q.qsize())
print("Removing Elements:")
print(q.get())
print(q.get())
print(q.get())
print("Empty or Not??",q.empty())
print(q.get())
print("Empty or Not??",q.empty())
print("Size of Queue:",q.qsize())
3) Implement Linear Search compute space and time complexities,
plot graph using asymptomatic notations.

import time
import numpy as np
from matplotlib import pyplot as plt

def linear_search(A,x):
for i in range(0, len(A)):
if A[i] == x:
print("search is success at possition",i)
return
print("Search is not success")

elements = np.array([i*1000 for i in range(1,40)])

plt.xlabel('List Length')
plt.ylabel('Time Complexity')
times = list()
for i in range(1, 40):
start = time.time()
a = np.random.randint(1000, size=i*1000)
linear_search(a,1)
end=time.time()
times.append(end - start)
print("time taken for linear search in ", i*1000,"Elements is", end -
start,"s")

plt.plot(elements, times, label = "Linear Search")


plt.grid()
plt.legend()
plt.show()
4) Write a linear search algorithm and give an example for that
algorithm.

# Algorithm:
LinearSearch(array, key)
for each item in the array
if item == value
return its index

# Program:

def linearSearch(array, n, x):


for i in range(0, n):
if (array[i] == x):
return i
return -1

array = [2, 4, 0, 1, 9]
x = 1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)

5) Implement Bubble,Selection,insertion sorting algorithms compute


space and time complexities, plot graph using asymptomatic
notations.

import time
import numpy as np
from matplotlib import pyplot as plt
# Selection Sort
def selectionSort(array):
i = 0
while i<len(array):
j = i
k = i+1
while k<len(array):
if array[k]<array[j]:
j=k
k=k+1
array[i],array[j]=array[j],array[i]
i=i+1

# 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

# Bubble Sort
def BubbleSort(array):
n=len(array)-1
while n>=1:
i=0
while i<n:
if array[i]>array[i+1]:
array[i],array[i+1]=array[i+1],array[i]
i = i+1
n=n-1
# Main
sorts=[
{
"name":"Selection Sort",
"sort": lambda arr:selectionSort(arr)
},
{
"name":"Insertion Sort",
"sort":lambda arr:insertionSort(arr)
},
{
"name":"bubble sort",
"sort":lambda arr:BubbleSort(arr)
},
]

elements = np.array([i*1000 for i in range(1,5)])

plt.xlabel('List Length')
plt.ylabel('Time Complexity')
for sort in sorts:
times = list()
start_all = time.time()
for i in range(1,5):
start = time.time()
a=np.random.randint(1000, size = i*1000)
sort["sort"](a)
end = time.time()
times.append(end - start)
print(sort["name"], "Sorted", i * 1000, "Elements in", end - start, "s")

end_all=time.time()
print(sort['name'],"Sorted Elements in",end_all - start_all, "s")
plt.plot(elements, times, label = sort["name"])
plt.grid()
plt.legend()
plt.show()
6) Sort the array using any three sorting techniques.
[22,-11,33,88,77,66,-64,44,56]

def bubbleSort(array):
for i in range(len(array)):
swapped = False

for j in range(0, len(array) - i - 1):


if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp

swapped = True

if not swapped:
break

data = [22,-11,33,88,77,66,-64,44,56]
print('Unsorted Array:\n', data)
bubbleSort(data)

print('Sorted Array in Ascending Order:')


print(data)

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 = [22,-11,33,88,77,66,-64,44,56]
print('Unsorted Array:\n', arr)
insertionSort(arr)

print ("Sorted Array in Ascending Order:")


print(data)
for i in range(len(arr)):
print ("%d" %arr[i])

def selectionSort(array, size):


for step in range(size):
min_idx = step
for i in range(step + 1, size):
if array[i] < array[min_idx]:
min_idx = i

(array[step], array[min_idx]) = (array[min_idx], array[step])

data = [22,-11,33,88,77,66,-64,44,56]

print("Unsorted Array is: \n",data)


size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)
7) Write a python program to implement binary search tree and its
Operations
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

def insert(root, key):


if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root

def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)

r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)

inorder(r)
8) Generate the 10 sequence of Fibonacci series using recursive
method.

# Python program to display the Fibonacci sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

9) Write a python code to insert a data at the beginning of the linked


list.
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None

# Print the linked list


def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval

def AtBegining(self,newdata):
NewNode = Node(newdata)

NewNode.nextval = self.headval
self.headval = NewNode

list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")

list.headval.nextval = e2
e2.nextval = e3

list.AtBegining("Sun")
list.listprint()

10) Write a python program to implement stack data structure.

class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
def peek(self):
return self.stack[-1]

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())

11) Write a python program to perform the operations on stack.

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))

12) Give an example to show the implementation of queue using list.

queue = []

# Adding elements to the queue


queue.append('Python')
queue.append('Java')
queue.append('HTML')

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)
13) Write a python program to demonstrate hash functions.

result = hash(21) # integer value


result2 = hash(22.2) # decimal value

print(result)
print(result2)

result = hash("javatpoint") # string value


result2 = hash((1,2,22)) # tuple value

print(result)
print(result2)

result = hash("javatpoint") # string value


result2 = hash([1,2,22]) # list

print(result)
print(result2)

class Student:
def __init__(self,name,email):
self.name = name
self.email = email

student = Student("Arun", "arun@abc.com")


result = hash(student) # object
print(result)

You might also like