Professional Documents
Culture Documents
ADDS JURY End Term Assignment
ADDS JURY End Term Assignment
➢
➢
➢
➢
➢
➢
➢
➢
Python is an open source, general purpose programming language that is easy to
read and powerful. It is an interpreted language, which do not need to be
compiled to run. Python is a high level language that will make a programmer
focus on what to do instead of how to do. Python has been designed to emphasize
on code readability with its significant use of whitespace. The simplicity of Python
language is that the code is Laconic and understandable even to those who have
never written it.
The uses of Python are for websites and web development, desktop GUI
applications development, automation scripts, complex calculation systems, life
support management systems, Games, Robotics, Scientific Computing, Natural
Learning Language and many more. It is designed with features to facilitate data
analysis and visualization.
runtime, like PHP or PERL, so you don’t have to compile the program before
execution.
▪ Features :
• Storing data
• Managing resources and services.
• Data exchange.
• Ordering and sorting
• Indexing.
• Searching
• Scalability
▪ Python Specific Data Structures:
These data structures are specific to python language and they give greater
flexibility in storing different types of data and faster processing in python
environment.
• List: It is similar to array with the exception that the data elements
can be of different data types. You can have both numeric and
string data in a python list.
• Tuple: Tuples are similar to lists but they are immutable which
means the values in a tuple cannot be modified they can only be
read.
• Dictionary: The dictionary contains Key-value pairs as its data
elements
• Linked lists :are best if a program is managing a collection of
items that don't need to be ordered, constant time is required for
adding or removing an item from the collection and increased
search time is OK.
• Stacks: are best if the program is managing a collection that
needs to support a LIFO order.
• Queues: should be used if the program is managing a collection
that needs to support a FIFO order.
• Binary trees :are good for managing a collection of items with a
parent-child relationship, such as a family tree.
• Binary search trees: are appropriate for managing a sorted
collection where the goal is to optimize the time it takes to find
specific items in the collection.
• Graphs: work best if the application will analyze connectivity and
relationships among a collection of individuals in a social media
network.
➢
o Description
The program takes a list and key as input and finds the index of the key in
the list using linear search.
It compares each and every element with the value that we are searching
for. If both are matched, the element is found, and the algorithm returns
the key's index position.
o Solution
o Source code
o Problem explanation
Case 1: Case 2:
Enter the list of numbers: 4 5 3 7 Enter the list of numbers: 3 5 6
The number to search for: 7 The number to search for: 2
7 was found at index 3. 2 was not found.
o Description
A list of items is given in random order, and we would like to arrange the
items in an orderly manner
Bubble sort is also known as sinking sort. It is a simple sorting algorithm
that continuously steps through the list to be sorted, comparing each pair
of adjacent items and swapping them if they are not in the correct order.
The steps are repeated until no more swaps are needed, which is when the
list is sorted.
o Solution
IV. Inside the inner loop, if the elements at indexes j and j + 1 are out
of order, then swap them.
V. If in one iteration of the inner loop there were no swaps, then the
list is sorted and one can return prematurely.
o Source code
def bubble_sort(list1):
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
list1[j],list1[j+1] = list1[j+1], list1[j]
return list1
o Problem explanation
1. Theuser is prompted to enter a list of numbers.
2. The list is passed to the bubble_sort function.
3. The sorted list is displayed.
Case 2:
Case 1:
Enter the list of numbers: 7 3 1 -5 2 10
Enter the list of numbers: 4 2 38 10 5
Sorted list: [-5, 1, 2, 3, 7, 10]
Sorted list: [2, 4, 5, 10, 38]
o Description
The program creates a queue and allows the user to perform enqueue and
dequeue operations on it.
queue is a linear data structure that stores items in First In First Out (FIFO)
manner. With a queue the least recently added item is removed first
o Solution
I. Create a class Queue with instance variable items initialized to an empty list.
II. Define methods enqueue, dequeue and is_empty inside the class Queue.
III. The method enqueue appends data to items.
IV. The method dequeue dequeues the first element in items.
V. The method is_empty returns True only if items is empty.
VI. Create an instance of Queue and present a menu to the user to perform
operations on the queue.
o Source code
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def dequeue(self):
return self.items.pop(0)
q = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
elif operation == 'dequeue':
if q.is_empty():
print('Queue is empty.')
else:
print('Dequeued value: ', q.dequeue())
elif operation == 'quit':
break
o Problem explanation
1. An instance of Queue is created.
the queue.
o Runtime test case
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Queue is empty.
enqueue <value>
dequeue
quit
What would you like to do? enqueue 7
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued value: 7
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Queue is empty.
enqueue <value>
dequeue
quit
What would you like to do? quit
o Description
The program creates a Graph data structure and allows the user to add vertices
and edges to it
A graph can be easily presented using the python dictionary data types. We
represent the vertices as the keys of the dictionary and the connection between
the vertices also called edges as the values in the dictionary.
Take a look at the following graph −
V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
o Solution
IV. points_to is a dictionary with keys being the Vertex objects that the
current object points to.
V. Each such Vertex object pointed to by the current object is mapped
to the weight of the corresponding directed edge.
VI. The class Vertex provides methods to get the key, to add a
neighbour, to get all neighbours, to get the weight of a directed
edge and to test whether a vertex is a neigbour of the current
Vertex object.
IX. The class Graph provides methods to add a vertex with a given key,
get the Vertex object with a given key, test whether a vertex with a
given key is in the Graph, add an edge between two vertices given
their keys and weight and test whether an edge exists between two
vertices given their keys. The __iter__ method is implemented to
allow iteration over the Vertex objects in the graph.
X. If whenever edge (u, v) is added to the graph, the reverse edge (v,
u) is also added, then this would become the implementation of an
undirected graph.
o Source code
class Graph:
def __init__(self):
self.vertices = {}
def add_vertex(self, key):
vertex = Vertex(key)
self.vertices[key] = vertex
return self.vertices[key]
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
def add_neighbour(self, dest, weight):
self.points_to[dest] = weight
def get_neighbours(self):
return self.points_to.keys()
return self.points_to[dest]
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> [weight]')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
if len(do) == 5:
weight = int(do[4])
g.add_edge(src, dest, weight)
else:
g.add_edge(src, dest)
else:
print('Edge already exists.')
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
Menu
display
quit
Vertices: 1 2
Edges:
Vertices: 1 2 3
Edges:
Vertices: 1 2 3
Edges:
Root or Data
Left Child
Right Child
o Solution
I. Define tree class which has three attributes namely: data left and
right. Here, left represents the left child of the tree and right
represents the right child of the tree.
II. When a tree is created, data will pass to data attribute of the tree
and both left and right will be set to null.
III. Define another class which has an attribute root.
IV. Root represents the root node of the tree and initialize it to null.
VI. It checks whether the root is null, which means the tre e is empty.
It will add the new node as root.
IX. First, it checks whether a node has a left and right child. If yes, it
will add both nodes to queue.
* If the left child is not present, it will add the new node as the
left child.
* If the left is present, then it will add the new node as the right
child
o Source code
class Tree:
self.left = None
self.right = None
self.data = data
if self.data:
if self.left is None:
self.left = Tree(data)
else:
self.left.insert(data)
if self.right is None:
self.right = Tree(data)
else:
self.right.insert(data)
else:
self.data = data
def getTree(self):
if self.left:
self.left.getTree()
print( self.data),
if self.right:
self.right.getTree()
root = Tree(30)
root.insert(15)
root.insert(35)
root.insert(9)
root.insert(28)
root.insert(40)
root.getTree()
o Problem explanation
Case 1
Root value =30
Insert (a) , a =15
Insert (b) , b =35
Insert (c) , c =9
Insert (d) , d =28
Insert (e) , e =40
9
15
28
30
35
40
➢
o Description
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or
First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and
an element is removed from that end only. The insert and delete operations are
often called push and pop.
The program creates a stack and allows the user to perform push and pop
operations on it.
o Solution
o Source code
class Stack_struct:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def delete_elements(self):
return self.items.pop()
my_instance = Stack_struct()
while True:
print('Push <value>')
print('Pop')
print('Quit')
my_input = input('What operation would you like to perform ? ').split()
my_op = my_input[0].strip().lower()
if my_op == 'push':
my_instance.add_elements(int(my_input[1]))
elif my_op == 'pop':
if my_instance.check_empty():
print('The stack is empty')
else:
print('The deleted value is : ', my_instance.delete_elements())
elif my_op == 'Quit':
break
o Problem explanation
1. An instance of Stack is created.
2. The user is presented with a menu to perform push and pop operations on the
stack.
3. The chosen operation is performed by calling the corresponding method of the
stack.
Push <value>
Pop
Quit
What operation would you like to perform ? push 2
Push <value>
Pop
Quit
What operation would you like to perform ? push 8
Push <value>
Pop
Quit
What operation would you like to perform ? push 4
Push <value>
Pop
Quit
What operation would you like to perform ? pop
The deleted value is : 4
Push <value>
Pop
Quit
What operation would you like to perform ?
THANK YOU