0% found this document useful (0 votes)
28 views8 pages

Extracting Uppercase Letters and Stack Operations in Python

The document contains multiple Python programming tasks involving stack operations. It includes functions to push and pop elements based on specific criteria, such as extracting uppercase letters, filtering visitors by age and gender, managing student records, and handling kitchen items based on price. Each task is accompanied by example data and expected output.

Uploaded by

yamunarthee22
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)
28 views8 pages

Extracting Uppercase Letters and Stack Operations in Python

The document contains multiple Python programming tasks involving stack operations. It includes functions to push and pop elements based on specific criteria, such as extracting uppercase letters, filtering visitors by age and gender, managing student records, and handling kitchen items based on price. Each task is accompanied by example data and expected output.

Uploaded by

yamunarthee22
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

1.

Thushar received a message(string) that has upper case and lower-


case alphabet.

He want to extract all the upper case letters separately .Help him to do his
task

by performing the following user defined function in Python:

a) Push the upper case alphabets in the string into a STACK

b) Pop and display the content of the stack.

For example:

If the message is “All the Best for your Pre-board Examination”

The output should be : E P B A

def push(s,ch):

[Link](ch)

def pop(s):

if s!=[]:

return [Link]()

else:

return None

string="All the Best for your Pre-board Examination"

st=[]

for ch in string:

if [Link]():

push(st,ch)

while True:

item=pop(st)

if item!=None:

print(item,end= ' ')

else:

break
2. A nested list contains the data of visitors in a museum. Each of the
inner lists contains

the following data of a visitor:

[V_no (int), Date (string), Name (string), Gender (String M/F), Age (int)]

Write the following user defined functions to perform given operations on


the stack

named "status":

(i) Push_element(Visitors) - To Push an object containing Gender of visitor


who

are in the age range of 15 to 20.

(ii) Pop_element() - To Pop the objects from the stack and count and
display the

number of Male and Female entries in the stack. Also, display “Done”
when

there are no elements in the stack.

For example: If the list of Visitors contains:

[['305', "10/11/2022", “Geeta”,"F”, 35],

['306', "10/11/2022", “Arham”,"M”, 15],

['307', "11/11/2022", “David”,"M”, 18],

['308', "11/11/2022", “Madhuri”,"F”, 17],

['309', "11/11/2022", “Sikandar”,"M”, 13]]

The stack should contain

The output should be:

Female: 1

Male: 2

Done

visitors=[['305', '10/11/2022', 'Geeta','F', 15],['306', '10/11/2022',


'Arham','M',
15],['307', "11/11/2022", 'David','M', 18],['308', "11/11/2022",
'Madhuri','F',

17]]

status=[]

def push_element(visitors):

global status

for i in visitors:

if i[4]>=15 and i[4]<=20:

[Link](i[3])

def pop_element():

global status

m,f=0,0

if status!=[]:

r=[Link]()

if r=='F':

f+=1

else:

m+=1

print("Female :",f)

print("Male :",m)

print("Done")

push_element(visitors)

pop_element()

3. [Link] has created a list of elements. Help him to write a


program in

python with functions, PushEl (S,element) and PopEl (S) to add a new

element and delete an element from a List of element named ‘S’


considering

them to act as push and pop operations of the Stack data structure . Push
the
element into the stack only when the element is divisible by 4.

For eg:if L=[2,5,6,8,24,32]

then stack content will be

32 <- Top

24

N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]

def PUSHEl(S,N):

[Link](N)

def POPEl(S):

if S!=[]:

return [Link]()

else:

return None

ST=[]

for k in N:

if k%4==0:

PUSHEl(ST,k)

while True:

if ST!=[]:

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

else:

break

4. A list contains following record of a student:

[student_name, age, hostel]

Write the following user defined functions to perform given operations on


the

stack named ‘stud_details’:


(i) Push_element() - To Push an object containing nameand

age of students who live in hostel “Ganga” to the stack

(ii) Pop_element() - To Pop the objects from the stack and display

them. Also, display “Stack Empty” when there are no elements in

thestack.

For example:

If the lists of customer detailsare:

[“Barsat”,17,”Ganga”]

[“Ruben”, 16,”Kaveri”]

[“Rupesh”,19,”Yamuna”]

The stack should contain

[“Barsat”,17,”Ganga”]

The output should be:

[“Barsat”,17,”Ganga”]

Stack Empty

stud_details = []

def push_element(lis):

for student in lis:

if student[2] == "Ganga":

stud_details.append([student[0], student[1]])

def pop_element():

while len(stud_details) > 0:

print(stud_details.pop())

print("Stack Empty")

lis = [["Barsat", 17, "Ganga"], ["Ruben", 16, "Kaveri"], ["Rupesh", 19,


"Yamuna"]]

push_element(lis)

pop_element()
5. A list named as Record contains following format of for students:

[student_name, class, city].

Write the following user defined functions to perform given operations on


the

stack named ‘Record’:

(i) Push_record(Record) – To pass the list Record = [ ['Rahul', 12,'Delhi'],

[‘Kohli',11,'Mumbai'], ['Rohit',12,'Delhi'] ] and then Push an object


containing

Student name, Class and City of student belongs to ‘Delhi’ to the stack
Record

and display and return the contents of stack

(ii) Pop_record(Record) – To pass following Record [[“Rohit”,”12”,”Delhi”]

[“Rahul”, 12,”Delhi”] ] and then to Pop all the objects from the stack and
at last

display “Stack Empty” when there is no student record in the stack. Thus
the

output should be: -

[“Rohit”,”12”,”Delhi”]

[“Rahul”, 12,”Delhi”]

Stack Empty

dict_product= [ ['Rahul', 12,'Delhi'],

['Kohli',11,'Mumbai'], ['Rohit',12,'Delhi'] ]

rec=[]

def Push_record(d):

for i in d:

if i[2]=="Delhi":

[Link](i)

def Pop_record():

while True:
if len(rec)>0:

print([Link]())

else:

print(“stack empty”)

break

Push_record(dict_product)

Pop_record()

6. Write a function in Python, Push(KItem),where KItem is a dictionary


containing

the details of Kitchen items– {Item:price}.

The function should push the names of those items in a stack which have
price less

than 100. Also display the average price of elements pushed into the
stack. For example: If the dictionary contains the following data:

{"Spoons":116,"Knife":50,"Plates":180,"Glass":60}

The stack should contain

Glass

Knife

The output should be:

The average price of an item is 55.0

def Push(KItem):

stack = []

total_price = 0

count = 0

for item, price in [Link]():

if price < 100:

[Link](item)
total_price += price

count += 1

# Display items in the stack

for item in stack:

print(item)

# Calculate and display average price

if count > 0:

average = total_price / count

print("The average price of an item is", average)

else:

print("No items with price less than 100.")

KItem = {"Spoons":116, "Knife":50, "Plates":180, "Glass":60}

Push(KItem)

Common questions

Powered by AI

User-defined functions for handling stack operations in Python provide modularity and encapsulation, making the code easier to understand and maintain. They allow program-specific operations, such as pushing only certain elements to the stack based on a condition (e.g., age range, city, item price). This encapsulation ensures that stack operations are consistent and can be reused across various parts of the program, improving efficiency and reducing code duplication .

Stack operations are efficient for sequential access patterns typical in Last In, First Out (LIFO) scenarios, differing by data structure. For lists and nested lists, stack operations like push and pop are convenient for data processing where the last element must be accessed first. When applied to dictionaries, stack operations can filter and manage keys based on conditions such as the price range in a dictionary of items. The efficiency of stacks is primarily in their O(1) time complexity for pushing and popping, making them ideal for applications needing repeated insertions and deletions .

To manage a nested list to count and display gender distribution, one can use a stack to store gender data for visitors in a specified age range and then pop the data from the stack. First, iterate through the nested list of visitors, and push the gender of visitors aged 15 to 20 onto the stack. Next, pop each gender from the stack while counting occurrences of male and female visitors until the stack is empty. Finally, display the number of males and females and a 'Done' message once the stack is empty .

The procedural logic involves iterating through a list of student records, checking for a specific condition (e.g., city), and using a stack to manipulate and display records. First, iterate over the list of records and push only those records onto the stack that match a specific city. Then, pop each record from the stack to display its contents until the stack is empty, signaling this event with a "Stack Empty" message. This approach ensures that only relevant records are stored for further use, making it efficient for operations only requiring data meeting certain criteria .

Python's stack operations can facilitate the calculation of average prices by filtering items based on conditions (e.g., price below a threshold) and using those items for further calculations. By pushing the names of items with prices less than a given value onto a stack and maintaining a running total and count of these items' prices, one can easily calculate the average after processing. The stack storage allows direct management of filtered data, making operations like displaying and aggregating simple and effective .

User-defined functions for stack-based text filtering in Python provide structured and reusable logic for data manipulation tasks. They allow specific data to be isolated, such as extracting and reversing uppercase letters from a string using stack operations. Through functions, this operation becomes repeatable and consistent, facilitating code reuse and reducing errors. Additionally, encapsulation through functions improves code readability and maintainability by delineating logic specifically tailored for stack-oriented string operations .

To maintain data integrity and efficiency, strategies for stack operations with nested lists include validating inputs and conditions accurately before performing stack push operations. This ensures only relevant data is handled, reducing unnecessary processing. Additionally, using clear and effective conditional checks (e.g., age limits) ensures only eligible records are pushed onto the stack. During popping, maintaining count variables or use flags can help track data handling progress and ensure all operations are accurately performed and logged, minimizing chances of data or process errors .

Stacks are particularly advantageous for managing datasets with age restrictions because they offer efficient LIFO processing for selectively storing and retrieving data. In age-restricted datasets, such as museum visitor records, only relevant data entries (e.g., ages within a specific range) are pushed onto the stack, facilitating focused data handling. This selective approach optimizes memory use and processing time as only necessary records are handled during subsequent stack operations, like counting gender distributions .

Stacks are useful for managing records of individuals in specified locations by providing straightforward operations for conditional data handling. For example, in managing student records, the procedure involves iterating over records and using a stack to push those with a certain locality (like 'Ganga'). The stack efficiently groups these records, which can then be popped to display or further process the data. This method allows for clear delineation and handling of relevant subsets within larger datasets, ensuring efficient, targeted operations .

Stack operations can be used to filter data by pushing only the elements that meet specific conditions onto the stack, and later popping them to display or process. For example, elements divisible by 4 can be selectively pushed onto a stack from a list. Similarly, student or visitor records meeting specific criteria (like age or location) can be pushed onto a stack, allowing efficient filtering and conditional operations using simple push and pop operations .

You might also like