0% found this document useful (0 votes)
61 views9 pages

Stack Operations in Python Functions

The document provides 13 questions related to implementing stack operations in Python using functions. The questions cover defining functions for PUSH and POP operations to add and remove elements from a stack implemented as a list. Elements that can be pushed and popped include numbers, strings, tuples, lists, and dictionaries. Functions are also defined to check if a stack is empty.

Uploaded by

Aman Singh
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)
61 views9 pages

Stack Operations in Python Functions

The document provides 13 questions related to implementing stack operations in Python using functions. The questions cover defining functions for PUSH and POP operations to add and remove elements from a stack implemented as a list. Elements that can be pushed and popped include numbers, strings, tuples, lists, and dictionaries. Functions are also defined to check if a stack is empty.

Uploaded by

Aman Singh
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

[Link] a function in Python PUSH_IN(L), where L is a list of numbers.

From this list, push all even


numbers into a stack which is implemented by using another list.

top=-1

stk=[]

def PUSH_IN(L): # Allow additions to the stack

for i in L:

if i%2==0:

[Link](i)

top=len(stk)-1

( ½ marks for correct function header)

( 1 mark for correct accessing of list elements)

( ½ mark for correct condition for even number)

( ½ mark for applying append() correctly)

( ½ mark for assignment in variable top)

[Link] a function in Python POP_OUT(Stk), where Stk is a stack implemented by a list of numbers. The
function returns the value which is deleted/popped from the stack.

def isEmpty(stk): # checks whether the stack is empty or not

if stk==[]:

return True

else:

return False

def POP_OUT(stk):

if isEmpty(stk): # verifies whether the stack is empty or not

print("Stack Underflow")

else: # Allow deletions from the stack

item=[Link]()
if len(stk)==0:

top=-1

else:

top=len(stk)

return item

( ½ marks for correct POP_OUT() function header)

( ½ mark for checking empty stack status)

( ½ mark for removing item for stack )

( 1 mark for assignment in variable top)

( ½ mark for returning the deleted item)

3. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers
divisible by 5 into a stack implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.

def PUSH(Arr,value):

s=[]

for x in range(0,len(Arr)):

if Arr[x]%5==0:

[Link](Arr[x])

if len(s)==0:

print("Empty Stack")

else:

print(s) (3 M for correct code)

4. Write a function in Python POP(Arr), where Arr is a stack implemented by a list of numbers. The
function returns the value deleted from the stack.

def popStack(st) : # If stack is empty

if len(st)==0:

print("Underflow")
else:

L = len(st)

val=st[L-1]

print(val)

[Link](L-1) (3 M for correct code)

5. Pramod has created a dictionary containing EMPCODE and SALARY as key value pairs of 5

Employees of Parthivi Constructions. Write a program, with separate user defined functions to

perform the following operations:

● Push the keys (Employee code) of the dictionary into a stack, where the corresponding value

(Salary) is less than 25000.

● Pop and display the content of the stack.

For example:

If the sample content of the dictionary is as follows:

EMP={"EOP1":16000, "EOP2":28000, "EOP3":19000,"EOP4":15000, "EOP5":30000}

The output from the program should be:

EOP4 EOP3 EOP1

EMP={"EOP1":16000, "EOP2":28000, "EOP3":19000, "EOP4":15000, "EOP5":30000}

def PUSH(S,N):

[Link](N)

def POP(S):

if S!=[]:

return [Link]()

else:

return None

ST=[]
for k in EMP:

if EMP[k]<25000:

PUSH(ST,k)

while True:

if ST!=[]:

print(POP(ST),end=" ")

else:

break

[Link] has a list containing 10 integers. You need to help him create a program with separate user
defined functions to perform the following operations based on this list.

● Traverse the content of the list and push the odd numbers into a stack.

● Pop and display the content of the stack.

For Example:

If the sample Content of the list is as follows:

Num=[31, 55, 76, 89, 21, 45, 76, 68 ]

Sample Output of the code should be:

45 21 89 31

Num=[31, 55, 76, 89, 21, 45, 76, 68 ]

def PUSH(S,N):

[Link](N)

def POP(S):

if S!=[]:

return [Link]()

else:

return None
ST=[]

for k in N:

if k%2!=0:

PUSH(ST,k)

while True:

if ST!=[]:

print(POP(ST),end=" ")

else:

break

[Link] students of class XII wants to enter details of student’s- Rollno, Name and grade in a stack.

Help him to write Push() methods in Python to add student’s details. Display the student’s details.

def push(stack):

s=[]

[Link](input(“Enter student rollno?”))

[Link](raw_input(“Enter student name”))

[Link](raw_input(“Enter student grade”))

[Link](s)

def display (stack):

l=len(stack)

print “STACK CONTENTS”

for i in range(l-1,-1,-1):

print stack[i]

stack=[]

print “Creating Stack”

n = input(“Enter the number of students”)


for i in range(n):

student = []

[Link](input(“Enter student rollno?”))

[Link](raw_input(“Enter student name”))

[Link](raw_input(“Enter student grade”))

stack, append(student) push(stack)

display(stack)

[Link] a program to implement a stack for the students(studentno, name). Just

implement Pop and display.

stk=[]

top=-1

def POP():

if(top==-1):

print(“NO STUDENT DATA”)

else:

print(“Student details are:”, [Link]())

top=len(stk)-1

def display():

if(top==-1):

print(“NO STUDENT DATA”)

else:

t=len(stk)-1

print(stk[t])

for i in range(t-1,-1,-1):

print(stk[i])
display()

POP()

9. Write a function in python, MakePush(Package) and MakePop(Package) to add a new Package and
delete a Package from a List of Package Description, considering them to act as push and pop operations
o def MakePush(Package):

a=int(input("enter package title : "))

[Link](a)

def MakePop(Package):

if (Package==[]):

print( "Stack empty")

else:

print ("Deleted element:",[Link]())

10. Write a function in python, Push(Stu) and MakePop(Stu) to add a new student and delete student
from a List of Stu contain rollno, Sname and Class as list, considering them to act as push and pop
operations of the Stack data structure

def Push(Stu):

rollno=int(input("enter package title : "))

Sname=int(input("enter package title : "))

Class=int(input("enter package title : "))

info=[rollno,Sname,Class]

[Link](info)

def Pop(Stu):

if (Stu==[]):

print( "Stack empty")


else:

print ("Deleted element:",[Link]())

11. Write a function in python, Push(Package) and Pop(Package) to add details of employee contain
information (Empid, Ename and Salary) in the form of tuple in Package and delete a Package from a List
of Package Description, considering them to act as push and pop operations of the Stack data structure

def Push(Package):

Empid=int(input(“Enter Id of Employee: "))

Ename=input(“Enter Name of employee”)

Salary= int(input(“Enter Salary of an employee”))

T=(Empid, Ename ,Salary)

[Link](T)

def Pop(Package):

if (Package==[]):

print( "Stack empty")

else:

print ("Deleted element:",[Link]())

12. Write a user define function to push an item of integer type into stack (function to push information
of student include rollno and name in the form of list/tuple or dictionary.)

PUSH OPERATION ON STACK

// function to push an item of integer type into stack

stack=[ ]

def push (stack):

item=int(input(“Enter the values of item”))

[Link](item)

// function to push information of student include rollno and name in the


form of list, tuple, dictionary

stack=[ ]

def push (stack):

rollno=int(input(“Enter rollno of student”))

name =input(“Enter Name of student”)

item=(rollno, name) \\ [rollno, name] \\ {rollno : “name”} \\ as per the problem

[Link](item)

13 Write a function push (student) and pop (student) 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.

stk=[ ]

def push(stk):

student_name=input("Enter name of student")

[Link](student_name)

def pop(stk):

if(stk==[]):

print("Stack is empty")

else:

print("Deleted student name :",[Link]())

Common questions

Powered by AI

Pushing a non-integer type into a stack meant for integers could lead to logical errors during operations that assume numeric processing, such as arithmetic computations or data type conversions. These operations could fail or yield incorrect results, disrupting the program flow. To avoid this, input validation should be enforced before the push operation to ensure that only integers are accepted. Implementing a type-checking function or using structured exception handling in Python could prevent invalid type insertions, thus maintaining stack integrity.

The process involves using a custom push function to append a student's details to the stack. These details include the student's roll number, name, and grade, collected through user inputs. Each student's details are stored as a list within the stack. After pushing, the stack structure changes by having a new list as its topmost element, containing the information entered. This operation highlights how multiple layers of lists can exist within a single stack structure, each layer representing a set of student details.

Pushing odd numbers into a stack involves traversing a list and adding qualifying elements. When popping, elements are removed in reverse order of their addition, adhering to the LIFO principle. Stack underflow challenges arise when attempting to pop from an empty stack, resulting in attempted accesses to non-existent elements. The function checks for an empty stack to avoid underflow by preventing pops when no elements exist, thus managing stack operations safely. Incorporating these preventive checks is crucial for stable stack manipulation, avoiding runtime errors commonly associated with underflows in such operations.

Implementing a dynamic stack in Python for employee records involves adding and removing employee tuples dynamically. Practicality resides in Python’s inherent dynamic list capabilities, but considerations include ensuring data consistency and type control, as each tuple (Empid, Ename, Salary) should retain structural integrity across operations. Potential pitfalls include unchecked list sizes leading to memory overuse or neglecting tuple field validation. Enforcing constraints on input validation before adding tuple entries and maintaining clear documentation of operations can mitigate these issues. Overall, careful design and robust error handling are critical for implementing such data structures effectively.

When the POP function is called with an empty stack, it checks the stack's length. If the length is zero, indicating the stack is empty, it prints "Underflow" to inform the user that there is no element to pop. This message conveys that a stack underflow condition has occurred, and no elements were removed from the stack.

The POP_OUT method starts by checking if the stack is empty using the isEmpty function, which evaluates if the stack list is empty and returns True if it is, otherwise False. If the stack is not empty, the function proceeds to pop the last element. The method adjusts the 'top' variable to reflect the new top of the stack: it sets 'top' to -1 if the stack becomes empty after popping, otherwise, it sets 'top' to one less than the current stack length. It returns the popped item to ensure the function outputs the element that was removed from the stack. This flow ensures that stack integrity and underflow conditions are properly handled.

MakePush allows the addition of a new package by appending it to the list representing the stack. Given that stacks operate on Last In, First Out (LIFO) principles, the newly added package instantly becomes the new top of the stack. MakePop removes the top element, ensuring stack consistency. Potential issues concern handling large numbers of packages, where the stack might consume substantial memory without appropriate limitations or cleanup operations. This function assumes the input is always valid and does not handle exceptions, like incorrect types or non-numeric inputs for package titles, which could disrupt stack processing and cause runtime errors.

In a stack data structure following the LIFO (Last In, First Out) principle, the most recently added element is the first to be accessed or removed. For student details, this means the last set of input data entered gets processed first upon popping operations. This order is significant for scenarios such as undo operations, where the latest change is reversed first, or for maintaining historical record reversals. Also, this ordering facilitates backtracking algorithms where recent paths are tested first. Therefore, maintaining order in stack operations ensures logical consistency with how elements are accessed and manipulated.

The PUSH function evaluates each employee's salary from a dictionary of employees. It checks each 'Salary' against the threshold of 25000. If an employee's salary is less than 25000, their corresponding employee code (key) is pushed onto the stack. The condition ensures that only employee codes tied to lower salaries are included, focusing the stack's content on these specific data points. The influence of salary checks tailors the stack to hold only relevant employee identifiers based on the defined financial condition.

The PUSH_IN function must iterate through the list L and push only the even numbers into the stack. This requires checking if a number is even (i.e., divisible by 2), which involves using the condition `i%2==0`. If this condition is met, the number is appended to the stack, and the variable 'top' is updated to reflect the new top of the stack, which is the last element's index.

You might also like