0% found this document useful (0 votes)
5 views5 pages

Python Code for Search and Stack Operations

Uploaded by

Vishal Agnihotri
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)
5 views5 pages

Python Code for Search and Stack Operations

Uploaded by

Vishal Agnihotri
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

Q16: Write a python code to input a number and perform linear search or search

in a list.
Ans:
list1= [10, 20, 30,40,10,50,10]
element=int(input("Enter element to count:"))
l=len(list1)
for i in range(l):
if list1[i]== element:
print(element, "found at index",i)
break
else:
print(element," not present in the given list")
Q11: Writing Python program to add multiple record in a binary file.
Ans:
import pickle
def write():
file=open('[Link]','ab')
y='y'
while y=='y':
roll=int(input('Enter roll no.:'))
name=input('Enter name:')
marks=int(input('Enter Marks:'))
data=[roll,name,marks]
[Link](data,file)
y=input('Do you want to enter data again:')
[Link]()
Q13. Write a function push() and pop() to add a new student name and
remove a student name from a list student, considering them to act as
PUSH and POP operations of stack Data Structure in Python.
st=[ ]
def push():
y="y"
while y=="y":
sn=input("Enter name of student:")
[Link](sn)
y=input("Do you want to enter more name(y/n):")

def pop():
if(st==[]):
print("Stack is empty")
else:
print("Deleted student name :",[Link]())

Output:-
Q14. Write a function Push() which takes "name" as argument and add in a
stack named "MyStack". After calling push() three times, a message
should be displayed "Stack is Full"

st=[ ]
StackSize=3
def push():
y="y"
while y=="y":
sn=input("Enter name of student:")
if len(st)<StackSize:
[Link](sn)
else:
print("Stack is full!")
print(st)
break
y=input("Do you want to enter more name(y/n):")

Output:-
Q15: Julie has created a dictionary containing names and marks as key
value pairs of 6 students. Write a program, with separate user defined
functions to perform the following operations:
 Push the keys (name of the student) of the dictionary into a stack,
where the corresponding value (marks) is greater than 75.
 Pop and display the content of the stack.

R={"OM":76, "JAI":45, "BOB":89,"ALI":65, "ANU":90, "TOM":82}


def PUSH(S,N):
[Link](N)
def POP(S):
if S!=[]:
return [Link]()

ST=[]
for k in R:
if R[k]>75:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break

Output:

Common questions

Powered by AI

Using pickle for handling binary file operations in Python reflects the principles of serialization and abstraction. Pickle allows complex data structures to be easily saved and retrieved, abstracting away the underlying byte-level details. It is preferred in applications needing frequent saving/loading of Python objects without manual data conversion, such as saving machine learning model parameters or session data .

To add multiple records to a binary file in Python using pickling, the following steps are followed: Open the file in append binary mode ('ab'), use a loop to repeatedly accept user-inputted data, create a list of these values, and dump this list into the file using pickle.dump(). The loop can continue based on user input until no more records are needed. Finally, close the file to save changes .

In Python, a stack can be used to selectively handle dictionary keys whose values exceed a defined threshold. This is done by iterating through the dictionary, using a push function to add keys to a stack if their corresponding values meet the threshold condition. Popping from the stack retrieves keys in LIFO order, allowing actions on these criteria-matched elements .

Linear search is most appropriate when dealing with unsorted lists or when the data set is relatively small. In these scenarios, sorting the data (a prerequisite for other search algorithms like binary search) may not be efficient, and the simplicity of linear search makes it more advantageous. For instance, searching for an element in a list of user names or simple unsorted records are situations where linear search excels .

A fixed-size stack limits the number of elements it can store, preventing push operations beyond its capacity. Attempting to push more elements results in an error message indicating the stack is full, preventing data overflow. This enforces controlled data storage within predetermined limits, which can be essential for resource-constrained applications .

A programmer may choose to implement custom push and pop functions for enhanced clarity, control, or to impose additional constraints on operations. These functions can integrate custom error messages or behaviors, such as capacity limits or logging, aligning with specific application requirements beyond default list operations. Custom functions improve readability by explicitly highlighting stack operations in the code .

Linear search can be implemented by iterating through each element in the list and checking if it matches the target element. In Python, a for loop can be used along with an if statement to compare each list element with the target. If a match is found, the index is printed and the search terminates. If the element is not found after examining all items, a 'not present' message is displayed .

When managing a stack with student names using push and pop operations, each name added last would be the first to be removed, exemplifying the stack's LIFO (Last In, First Out) nature. This impacts data processing by ensuring the most recent data is accessed first, which is beneficial in applications like undo features in text editors or managing function calls in recursion .

User-defined functions facilitate stack operations in Python by encapsulating push and pop processes. The push function appends new elements to the list representing the stack, while the pop function removes and returns the last element. A conditional check ensures pop operations do not occur on an empty stack, displaying a message instead. This approach abstracts stack behavior from the underlying list data structure .

Using a dictionary to store student marks offers fast lookups, making it efficient to check conditions like marks being above a threshold. Coupling this with a stack allows for organizing keys based on certain criteria, facilitating structured data handling. The drawback is increased complexity if multiple conditions are needed, as this setup can become difficult to manage and debug compared to simpler data structures .

You might also like