0% found this document useful (0 votes)
8 views16 pages

Py6 (Rohit Asawale)

The document outlines a laboratory experiment for a Python programming course focused on data structures, including stacks, queues, graphs, trees, and various operations on lists, sets, dictionaries, tuples, and strings. It provides theoretical explanations, prerequisites, expected outcomes, and a menu-driven program implementation for performing operations on these data structures. The document concludes with an example of the program's output and a section for attendance and marks.

Uploaded by

exxo.711
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)
8 views16 pages

Py6 (Rohit Asawale)

The document outlines a laboratory experiment for a Python programming course focused on data structures, including stacks, queues, graphs, trees, and various operations on lists, sets, dictionaries, tuples, and strings. It provides theoretical explanations, prerequisites, expected outcomes, and a menu-driven program implementation for performing operations on these data structures. The document concludes with an example of the program's output and a section for attendance and marks.

Uploaded by

exxo.711
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/ 16

Sub: Skill Base Lab: Python Programming Course code: CSL405

Semester: IV Course: AI&DS

Laboratory no: 101 Name of subject teacher: Prof. Rajesh Khotre

Name of the Student: Aryan Fursule Roll no: VU2F2324032

Experiment No.06

A.1 Aim:

To implement a menu driven program for data structure using built in functions for stack and
queues and Double ended queue.

A.2 Prerequisite:

1. C,JAVA Language

A.3 Outcome:

After successful completion of this experiment students will be able to

. To develop program for data structure using built in functions in python

A.4 Theory& Procedure:

Stacks

A stack is a container of objects that are inserted and removed according to the Last-In-First-Out
(LIFO) concept. Think of a scenario where at a dinner party where there is a stack of plates, plates are
always added or removed from the top of the pile. In computer science, this concept is used for
evaluating expressions and syntax parsing, scheduling algortihms/routines, etc.

Stacks can be implemented using lists in Python. When you add elements to a stack, it is known as a
push operation, whereas when you remove or delete an element it is called a pop operation. Note that
you have actually have a pop() method at your disposal when you're working with stacks in Python:
Queue

A queue is a container of objects that are inserted and removed according to the First-In-First-Out
(FIFO) principle. An excellent example of a queue in the real world is the line at a ticket counter
where people are catered according to their arrival sequence and hence the person who arrives first is
also the first to leave.

Queues can be of many different kinds but in this tutorial only discusses the most basic type. Lists are
not efficient to implement a queue, because append() and pop() from the end of a list is fast. Also,
insertion at the end and deletion from the beginning of a list is not so fast since it requires a shift in
the element positions.

Graphs

A graph in mathematics and computer science are networks consisting of nodes, also called vertices
which may or may not be connected to each other. The lines or the path that connects two nodes is
called an edge. If the edge has a particular direction of flow, then it is a directed graph, with the
direction edge being called an arc. Else if no directions are specified, the graph is called an undirected
graph.

This may sound all very theoretical and can get rather complex when you dig deeper. However,
graphs are an important concept specially in Data Science and are often used to model real life
problems. Social networks, molecular studies in chemistry and biology, maps, recommender system
all rely on graph and graph theory principles.

You can do some cool stuff with graphs such as trying to find of there exists a path between two
nodes, or finding the shortest path between two nodes, determining cycles in the graph.

The famous "travelling salesman problem" is, in fact, about finding the shortest possible route that
visits every node exactly once and returns to the starting point. Sometimes the nodes or arcs of a
graph have been assigned weights or costs, you can think of this as assigning difficulty level to walk
and you are interested in finding the cheapest or the easiest path.

Trees

A tree in the real world is a living being with its roots in the ground and the branches that hold the
leaves, fruit out in the open. The branches of the tree spread out in a somewhat organized way. In
computer science, trees are used to describe how data is sometimes organized, except that the root is
on the top and the branches, leaves follow, spreading towards the bottom and the tree is drawn
inverted compared to the real tree.

To introduce a little more notation, the root is always at the top of the tree. Keeping the tree metaphor,
the other nodes that follow are called the branches with the final node in each branch being called
leaves. You can imagine each branch as being a smaller tree in itself. The root is often called the
parent

and the nodes that it refers to below it called its children. The nodes with the same parent are called
siblings. Do you see why this is also called a family tree?

Trees help in defining real world scenarios and are used everywhere from the gaming world to
designing XML parsers and also the PDF design principle is based on trees. In data science, 'Decision
Tree based Learning' actually forms a large area of research. Numerous famous methods exist like
bagging, boosting use the tree model to generate a predictive model. Games like chess build a huge
tree with all possible moves to analyse and apply heuristics to decide on an optimal move.

Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the
first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use
append(). To retrieve an item from the top of the stack, use pop() without an explicit index.
For example:

It is also possible to use a list as a queue, where the first element added is the first element
retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends
and pops from the end of list are fast, doing inserts or pops from the beginning of a list is
slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and
pops from both ends. For example:

5.1.3. List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make
new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a
certain condition.
Note that this creates (or overwrites) a variable named x that still exists after the loop

A list comprehension consists of brackets containing an expression followed by a for clause,


then zero or more for or if clauses. The result will be a new list resulting from evaluating the
expression in the context of the for and if clauses which follow it. For example, this listcomp
combines the elements of two lists if they are not equal:

Conclusion: Thus we perform Menu driven program for data structure using built in function for
link list, stack and queue.
PROGRAM:

def list_operations():

lst = []

while True:

print("\nList Operations:")

print("1. Append")

print("2. Remove")

print("3. Display List")

print("4. Reverse List")

print("5. Exit List Operations")

choice = int(input("Enter choice: "))

if choice == 1:

val = input("Enter value to append: ")

lst.append(val)

elif choice == 2:

if lst:

val = input("Enter value to remove: ")

if val in lst:

lst.remove(val)

else:
print("Value not found!")

else:

print("List is empty!")

elif choice == 3:

print("List:", lst)

elif choice == 4:

print("Reversed List:", lst[::-1])

elif choice == 5:

break

else:

print("Invalid choice! Try again.")

def set_operations():

s = set()

while True:

print("\nSet Operations:")

print("1. Add")

print("2. Remove")

print("3. Check if exists")

print("4. Display Set")

print("5. Exit Set Operations")

choice = int(input("Enter choice: "))


if choice == 1:

val = input("Enter value to add: ")

s.add(val)

elif choice == 2:

if s:

val = input("Enter value to remove: ")

s.discard(val)

else:

print("Set is empty!")

elif choice == 3:

val = input("Enter value to check: ")

print("Exists in set:", val in s)

elif choice == 4:

print("Set:", s)

elif choice == 5:

break

else:

print("Invalid choice! Try again.")

def dict_operations():

d = {}

while True:
print("\nDictionary Operations:")

print("1. Add Key-Value Pair")

print("2. Remove Key")

print("3. Get Value by Key")

print("4. Display Dictionary")

print("5. Exit Dictionary Operations")

choice = int(input("Enter choice: "))

if choice == 1:

key = input("Enter key: ")

value = input("Enter value: ")

d[key] = value

elif choice == 2:

if d:

key = input("Enter key to remove: ")

d.pop(key, None)

else:

print("Dictionary is empty!")

elif choice == 3:

key = input("Enter key to get value: ")

print("Value:", d.get(key, "Key not found!"))

elif choice == 4:
print("Dictionary:", d)

elif choice == 5:

break

else:

print("Invalid choice! Try again.")

def tuple_operations():

t = ()

while True:

print("\nTuple Operations:")

print("1. Create Tuple")

print("2. Concatenate Tuple")

print("3. Indexing in Tuple")

print("4. Exit Tuple Operations")

choice = int(input("Enter choice: "))

if choice == 1:

values = input("Enter comma-separated values: ").split(',')

t = tuple(values)

elif choice == 2:

if t:

values = input("Enter values to concatenate: ").split(',')


t += tuple(values)

else:

print("Create a tuple first!")

elif choice == 3:

if t:

idx = int(input("Enter index: "))

if 0 <= idx < len(t):

print("Element at index", idx, ":", t[idx])

else:

print("Index out of range!")

else:

print("Tuple is empty!")

elif choice == 4:

break

else:

print("Invalid choice! Try again.")

def string_operations():

s = ""

while True:

print("\nString Operations:")

print("1. Append to String")

print("2. Remove Last Character")


print("3. Reverse String")

print("4. Display String")

print("5. Exit String Operations")

choice = int(input("Enter choice: "))

if choice == 1:

val = input("Enter string to append: ")

s += val

elif choice == 2:

if s:

s = s[:-1]

else:

print("String is empty!")

elif choice == 3:

print("Reversed String:", s[::-1])

elif choice == 4:

print("String:", s)

elif choice == 5:

break

else:

print("Invalid choice! Try again.")


def main():

while True:

print("\nData Structure Operations:")

print("1. List")

print("2. Set")

print("3. Dictionary")

print("4. Tuple")

print("5. String")

print("6. Exit")

choice = int(input("Enter choice: "))

if choice == 1:

list_operations()

elif choice == 2:

set_operations()

elif choice == 3:

dict_operations()

elif choice == 4:

tuple_operations()

elif choice == 5:

string_operations()

elif choice == 6:
print("Exiting Program.")

break

else:

print("Invalid choice! Try again.")

if _name_ == "_main_":

main()

Output:

Data Structure Operations:

1. List

2. Set

3. Dictionary

4. Tuple

5. String

6. Exit

Enter choice: 2

Set Operations:

1. Add

2. Remove

3. Check if exists
4. Display Set

5. Exit Set Operations

Enter choice: 1

Enter value to add: Car

Set Operations:

1. Add

2. Remove

3. Check if exists

4. Display Set

5. Exit Set Operations

Enter choice: 1

Enter value to add: Bike

Set Operations:

1. Add

2. Remove

3. Check if exists

4. Display Set

5. Exit Set Operations

Enter choice: 3

Enter value to check: Car

Exists in set: True


Set Operations:

1. Add

2. Remove

3. Check if exists

4. Display Set

5. Exit Set Operations

Enter choice: 4

Set: {'Car', 'Bike'}

Set Operations:

1. Add

2. Remove

3. Check if exists

4. Display Set

5. Exit Set Operations

Enter choice: 5
DOP DOS R1 R2 R3 TOTAL SIGNATURE

ATTENDENCE CONDUCTION VIVA 10


MARKS
2 MARKS 4 MARKS 4
MARKS

You might also like