0% found this document useful (0 votes)
10 views51 pages

Python Functions for Common Tasks

The document provides a series of Python programming tasks, each with a specific aim and corresponding source code. The tasks include calculating factorials, summing divisible numbers, manipulating lists, handling employee data, calculating areas of shapes, and working with files. Additionally, it covers random number generation, word frequency counting, and binary file operations, showcasing various Python functions and techniques.

Uploaded by

Roshan Mohanmed
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)
10 views51 pages

Python Functions for Common Tasks

The document provides a series of Python programming tasks, each with a specific aim and corresponding source code. The tasks include calculating factorials, summing divisible numbers, manipulating lists, handling employee data, calculating areas of shapes, and working with files. Additionally, it covers random number generation, word frequency counting, and binary file operations, showcasing various Python functions and techniques.

Uploaded by

Roshan Mohanmed
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

1) Aim:- Write a function in python to find the factorial value

for the given number.

Source code:-

def fact(n):
f = 1
for i in range(1, n+1):
f*=i
return f
n = int(input("Enter a number: "))
print("Factorial of",n,"is", fact(n))

Output:-

Enter a number: 5
Factorial of 5 is 120
2)Aim:- Write a function Div3anddiv5() that takes 10
elements numeric tuple and returns the sum of elements
which are divisible by 3 and by 5

Source code:-

def Div3anddiv5(tuple):
sum = 0
for num in tuple:
if num%3==0 and num%5==0:
sum+=num
return sum
t = eval(input("Enter a tuple of numbers: "))
print("Sum: ",Div3anddiv5(t))

Output:-

Enter a tuple of numbers: (1, 5, 2, 6, 45, 25,


24, 12, 75, 100, 3, 15)
Sum: 135
3)Aim:- Write a function Digitsum() that takes a
number(minimum 3 digits) and returns its digit sum

Source code:-

def Digitsum(n):
sum = 0
for i in str(n):
sum += int(i)
return sum

num = input("Enter a number: ")


if len(num) < 3:
print("Number should be minimum 3 digits
long.")
else:
print("Digit sum: ", Digitsum(int(num)))

Output:-

Enter a number: 6732


Digit sum: 18
4)Aim:- Write the definition of a function Alter(A, N) in
python which should change all the multiples of 5 in the list
to 5 and rest of the elements as 0.

Source code:-

def Alter(A, N):


for i in range(N):
if A[i] % 5 == 0:
A[i] = 5
else:
A[i] = 0
return A

list = eval(input("Enter a list of numbers: "))


print("Original List:", list)
print("Modified List:", Alter(list, len(list)))​

Output:-

Original List: [35,13,597,435,236,8345,3738,235]


Modified List: [5, 0, 0, 5, 0, 5, 0, 5]
5)Aim:- Create a function showEmployee() in such a way that
it should accept employee name, and it’s salary and display
both, and if the salary is missing in function call it should
show it as 9000

Source code:-

def showEmployee(name, salary=9000):


print("Employee Name: " + name)
print("Salary: " + str(salary))
showEmployee(“John”)
showEmployee(“Richard”, 7500)

Output:-

Employee Name: John


Salary: 9000
Employee Name: Richard
Salary: 7500
6)Aim:- Write a menu driven program to calculate areas of
different shapes(circle, rectangle, triangle) using functions.

Source code:-

def circleArea(r):
return [Link] * [Link](r, 2)
def rectArea(l, w):
return l * w
def triangleArea(b, h):
return 0.5 * b * h

print("MENU")
print("1. Area of Circle")
print("2. Area of Rectangle")
print("3. Area of Triangle")
print("4. Exit")

while True:
c = int(input("Enter your choice: "))
if c == 1:
r = int(input("Enter radius: "))
print("Area of Circle:", circleArea(r),
end="\n\n")
elif c == 2:
l = int(input("Enter length: "))
w = int(input("Enter width: "))
print("Area of Rectangle:", rectArea(l,
w), end="\n\n")
elif c == 3:
b = int(input("Enter base: "))
h = int(input("Enter height: "))
print("Area of Triangle:",
triangleArea(b, h), end="\n\n")
elif c == 4:
print("Exited", end="\n\n")
break
else:
print("INVALID CHOICE", end="\n\n")​

Output:-

MENU
1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
4. Exit
Enter your choice: 6
INVALID CHOICE

Enter your choice: 1


Enwr radius: 7
Area of Circle: 153.93804002589985

Enter your choice: 2


Enter length: 12
Enter width: 2
Area of Rectangle: 24
Enter your choice: 3
Enter base: 4
Enter height: 3
Area of Triangle: 6.0

Enter your choice: 4


Exited
7)Aim:- Write a program based on a random number
generation between 1 to 6 using a function.(number Guess
game, max 3 chances)

Source code:-

import random
randNum = [Link](1, 6)
def guess_number():
for i in range(3):
num = int(input("Guess a number between 1
and 6: "))
if num == randNum:
print("Congratulations!")
return
else:
print("Try again.")
print("Better luck next time!")
guess_number()​

Output:-

Guess a number between 1 and 6: 3


Try again.
Guess a number between 1 and 6: 2
Try again.
Guess a number between 1 and 6: 4
Try again.
Better luck next time!
Guess a number between 1 and 6: 3
Try again.
Guess a number between 1 and 6: 5
Try again.
Guess a number between 1 and 6: 1
Congratulations!
8)Aim:- Write a program to copy all the lines that begin with
the character “a” or “t” in a file “[Link]” and write those
lines to another file.

Source code:-

file = open("[Link]", "r")


newFile = open("[Link]", "w")
lines = [Link]()
for l in lines:
if l[0].lower() == "a" or l[0].lower() ==
"t":
[Link](l)
[Link]()
[Link]()
newFile = open("[Link]", "r")
print([Link]())
[Link]()

Output:-

[Link]

[Link]
9)Aim:- Write a menu driven program to perform the
following on a text file ‘[Link]’ using function:
[Link] the number of lines that are ending with letter ‘r’
[Link] the number of words
3. Read a random line from the file and display

Source code:-

import random as r
file = open("[Link]", "r")
lines = [Link]()
print("MENU")
print("1. Count number of lines ending with
'r'")
print("2. Count number of words")
print("3. Read random line from file and
display")
print("4. Exit")
while True:
choice = int(input("Enter a choice: "))
if choice == 1:
count = 0
for l in lines:
if [Link]().endswith('r'):
count += 1
print("Lines ending with 'r':", count)
elif choice == 2:
words = 0
for l in lines:
words += len([Link]())
print("Number of words:", words)
elif choice == 3:

print(lines[[Link](len(lines))].strip())
elif choice == 4:
[Link]()
print("Exited")
break
else:
print("INVALID CHOICE")

Output:-

[Link]

MENU
1. Count number of lines ending with 'r'
2. Count number of words
3. Read random line from file and display
4. Exit
Enter a choice: 1
Lines ending with 'r': 0
Enter a choice: 2
Number of words: 99
Enter a choice: 3
The sun dipped low behind the mountains, casting
long shadows across the valley below
Enter a choice: 4
Exited
10)Aim:- Write a menu driven program to perform the
following on a text file ‘[Link]’ using function:
[Link] the vowels
2. Count the number of uppercase letters and lowercase
letters
3. Count the digits
4. Count the spaces

Source code:-

file = open("[Link]", "r")


text = [Link]()
print("MENU")
print("1. Count vowels")
print("2. Count uppercase and lowercase
letters")
print("3. Count d")
print("4. Count spaces")
print("5. Exit")
while True:
c = int(input("Enter a choice: "))
if c == 1:
count = 0
for ch in text:
if ch in 'aeiouAEIOU':
count += 1
print("Number of vowels:", count)
elif c == 2:
u = 0
l = 0
for ch in text:
if [Link]():
u += 1
elif [Link]():
l += 1
print("Uppercase letters:", u)
print("Lowercase letters:", l)
elif c == 3:
d = 0
for ch in text:
if [Link]():
d += 1
print("Number of digit:", d)
elif c == 4:
s = 0
for ch in text:
if ch == ' ':
s += 1
print("Number of space:", s)
elif c == 5:
[Link]()
print("Exited")
break
else:
print("INVALID CHOICE")
Output:-

[Link]

MENU
1. Count vowels
2. Count uppercase and lowercase letters
3. Count d
4. Count spaces
5. Exit
Enter a choice: 1
Number of vowels: 161
Enter a choice: 2
Uppercase letters: 5
Lowercase letters: 449
Enter a choice: 3
Number of digit: 0
Enter a choice: 4
Number of space: 94
Enter a choice: 5
Exited
11)Aim:- Write a program to read the file ‘[Link]’ and
display the content where each word is separated by ‘#’​

Source Code:-

file = open("[Link]", "r")


text = [Link]()
[Link]()
words = [Link]()
output = '#'.join(words)
print(output)

Output:-

[Link]

The#sun#dipped#low#behind#the#mountains,#casting
#long#shadows#across#the#valley#below#The#air#ha
d#that#crisp#feeling,#as#if#the#earth#was#holdin
g#its#breath,#waiting#for#the#cool#embrace#of#ev
ening#Birds#sang#their#final#songs#of#the#day,#t
heir#melodies#echoing#off#the#cliffs#like#whispe
rs#of#old#stories#As#the#sky#shifted#from#golden
#to#violet,#the#first#stars#began#to#twinkle#fai
ntly,#as#though#they#were#shyly#making#their#pre
sence#known#It#was#a#moment#of#stillness,#where#
everything#seemed#to#align,#a#brief#pause#in#tim
e#before#the#night#fully#arrived
12)Aim:- Write a program to count a frequency of a word
entered by the user in the given file ‘[Link]’​

Source Code:-

file = open("[Link]", "r")


words = [Link]().split()
word = input("Enter word to count: ")
count = 0
for w in words:
if [Link]() == [Link]():
count += 1
print(count)
[Link]()

Output:-

[Link]

Enter word to count: the


11
13)Aim:- Write a program to display the words that are
having length more than 4 in the given file ‘[Link]’ using
function.​

Source Code:-

file = open("[Link]", "r")


text = [Link]()
[Link]()
for word in [Link]():
if len(word) > 4:
if word[-1] == ',':
print(word[:-1], end=' ')
else:
print(word, end=' ')

Output:-

[Link]

dipped behind mountains casting shadows across


valley below crisp feeling earth holding breath
waiting embrace evening Birds their final songs
their melodies echoing cliffs whispers stories
shifted golden violet first stars began twinkle
faintly though shyly making their presence known
moment stillness where everything seemed align
brief pause before night fully arrived
14)Aim:- Write a method showlines() in python to readlines
from text file‘[Link]’ and display the lines which do not
contain word 'the'.​

Source Code:-

file = open("[Link]", "r")


lines = [Link]()
[Link]()
for line in lines:
if "the" not in [Link]():
print([Link]())

Output:-

[Link]

It was a moment of stillness, where everything


seemed to align, a brief pause in time before
night fully arrived
15)Aim:- A text file “[Link]” contains alphanumeric text.
Write a program that reads this text file and writes to
another file “[Link]” the entire file except the numbers
or digits in the file.​

Source Code:-

file = open("[Link]", "r")


text = [Link]()
[Link]()
cleaned = ''
for ch in text:
if not [Link]():
cleaned += ch
file1 = open("[Link]", "w")
[Link](cleaned)
[Link]()

Output:-

[Link]

[Link]
16)Aim:-A binary file [Link] has structure (ID, NAME,
PRICE). Write the definition of a function WRITEREC() in
Python, to input data for records from the user and write
them to the file [Link]. Write the definition of a
function SHOWHIGH() in Python, which reads the records of
[Link] and displays those records for which the PRICE
is more than 500.​

Source Code:-

import pickle
def WRITEREC():
file = open("[Link]", "wb")
ID = int(input("Enter Plant ID: "))
NAME = input("Enter Plant Name: ")
PRICE = float(input("Enter Price: "))
record = (ID, NAME, PRICE)
[Link](record, file)
[Link]()
def SHOWHIGH():
try:
file = open("[Link]", "rb")
[Link](0)
while True:
record = [Link](file)
if record[2] > 500:
print("ID:", record[0], "Name:",
record[1], "Price:", record[2])
except EOFError:
[Link]()
print("End of file reached.")
print("Menu")
print("1. Add Plant Records")
print("2. Show Plants with Price > 500")
print("3. Exit")
while True:
ch = input("Enter a choice: ")
if ch == '1':
WRITEREC()
elif ch == '2':
SHOWHIGH()
elif ch == '3':
print("Exited")
break
else:
print("INVALID")

Output:-

Menu
1. Add Plant Records
2. Show Plants with Price > 500
3. Exit
Enter a choice: 1
Enter Plant ID: 1
Enter Plant Name: Basil
Enter Price: 200
Enter a choice: 1
Enter Plant ID: 2
Enter Plant Name: Tulsi
Enter Price: 50
Enter a choice: 1
Enter Plant ID: 3
Enter Plant Name: Cactus
Enter Price: 700
Enter a choice: 2
ID: 3 Name: Cactus Price: 700.0
End of file reached.
Enter a choice: 3
Exited
17)Aim:- A binary file “[Link]” has structure
(admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file
“[Link]” and display the details of those students
whose percentage is above 75. Also display number of
students scoring above 75%​

Source Code:-

import pickle
def writerec():
file = open("[Link]", "ab")
ad = int(input("Admission Number: "))
name = input("Name: ")
perc = float(input("Percentage: "))
record = (ad, name, perc)
[Link](record, file)
[Link]()
def countrec():
count = 0
try:
file = open("[Link]", "rb")
[Link](0)
while True:
record = [Link](file)
if record[2] > 75:
print("Admission No:",
record[0], "| Name:", record[1], "|
Percentage:", record[2])
count += 1
except EOFError:
[Link]()
print("Total students scoring above 75%:
", count)

print("MENU")
print("1. Add Student Records")
print("2. Show Students with >75%")
print("3. Exit")
while True:
ch = input("Enter choice: ")
if ch == '1':
writerec()
elif ch == '2':
countrec()
elif ch == '3':
print("Exited")
break
else:
print("INVALID")

Output:-

MENU
1. Add Student Records
2. Show Students with >75%
3. Exit
Enter choice: 1
Admission Number: 1
Name: Jon
Percentage: 90
Enter choice: 1
Admission Number: 2
Percentage: 70
Enter choice: 1
Admission Number: 3
Name: Ron
Percentage: 80
Enter choice: 2
Admission No: 1 | Name: Jon | Percentage: 90.0
Admission No: 3 | Name: Ron | Percentage: 80.0

Total students scoring above 75%: 2


Enter choice: 3
Exited
18)Aim:- Rehaan is a Python programmer. He has written a
code and created a binary file [Link] with student_id,
sname and marks. The file contains 10 records. He now has to
update a record based on the student_id entered by the user
and update the marks by 10%. Write a function updatestu() to
do this task.​

Source Code:-

import pickle
file = open("[Link]", "wb")
data =
[(100,"Jon",80),(101,"Bob",90),(102,"Ron",100),(10
3,"Rick",75),(104,"Rob",65),(105,"Gin",40),(106,"J
ill",20),(107,"Billy",35),(108,"Alex",85),(109,"Ja
ke",95),(110,"James",55)]
for rec in data:
[Link](rec, file)
[Link]()
def updatestu():
found = False
try:
file = open("[Link]", "rb")
records = []
while True:
record = [Link](file)
[Link](record)
except EOFError:
[Link]()
id = int(input("Enter Student ID: "))
for i in range(len(records)):
if records[i][0] == id:
temp = records[i][2]
records[i] = (id, records[i][1],
temp*1.1)
found = True
print("Mark updated for", id, "from",
temp, "to", records[i][2])
break
if not found:
print("ID not found.")
file = open("[Link]", "wb")
for rec in records:
[Link](rec, file)
[Link]()
def studel():
try:
file = open("[Link]", "rb")
records = []
while True:
record = [Link](file)
if record[2] >= 40:
[Link](record)
else:
print("Removed mark: ", record)
except EOFError:
[Link]()
file = open("[Link]", "wb")
for rec in records:
[Link](rec, file)
[Link]()
print("MENU")
print("1. Update Student Marks by 10%")
print("2. Delete Students with Marks < 40")
print("3. Exit")
while True:
ch = input("Enter your choice: ")
if ch == '1':
updatestu()
elif ch == '2':
studel()
elif ch == '3':
print("Exited")
break
else:
print("INVALID")

Output:-

MENU
1. Update Student Marks by 10%
2. Delete Students with Marks < 40
3. Exit
Enter your choice: 1
Enter Student ID: 104
Mark updated for 104 from 65 to 71.5
Enter your choice: 1
Enter Student ID: 100
Mark updated for 100 from 80 to 88.0
Enter your choice: 2
Removed mark: (106, 'Jill', 20)
Removed mark: (107, 'Billy', 35)
Enter your choice: 3
Exited
19)Aim:- Write a function studel() to delete the students who
have a percentage less than 40.​

Source Code:-

import pickle
import os
def stuwrite():
f1 = open('del_stu.dat', 'wb')
stu = {}
while True:
ad = int(input("Enter admission number: "))
name = input("Enter name: ")
per = float(input("Enter percentage: "))
stu['Admission Number'] = ad
stu['Name'] = name
stu['Percentage'] = per
[Link](stu, f1)
ch = input("Do you want to continue? ")
if ch == 'n':
break
[Link]()
stuwrite()
def delstu():
f1 = open('del_stu.dat', 'rb')
f2 = open('[Link]', 'wb')
flag = 0
try:
while True:
stu = [Link](f1)
if stu['Percentage'] < 40:
flag = 1
else:
[Link](stu, f2)
except EOFError:
if flag == 0:
print("No record found")
else:
print("Record found")
[Link]()
[Link]()
[Link]('del_stu.dat')
[Link]('[Link]', 'del_stu.dat')
delstu()

Output:-

Enter admission number: 1


Enter name: Ajay
Enter percentage: 78
Do you want to continue? y
Enter admission number: 2
Enter name: Behag
Enter percentage: 34
Do you want to continue? y
Enter admission number: 3
Enter name: Charan
Enter percentage: 67
Do you want to continue? y
Enter admission number: 4
Enter name: Drake
Enter percentage: 37
Do you want to continue? n
Record found
20)Aim:- Write a function COPY_REC() that copies all those
records from “[Link]” where the percentage is greater
than 85 into a new file [Link]​

Source Code:-

import pickle
def stuwrite():
f1=open('[Link]','wb')
stu={}
while True:
ad=int(input("Enter admission number: "))
name=input("Enter name: ")
per=float(input("Enter percentage: "))
stu['Admission Number']=ad
stu['Name']=name
stu['Percentage']=per
[Link](stu,f1)
ch=input("Do you want to continue? ")
if ch=='n':
break
[Link]()
stuwrite()
def copy():
f1=open('[Link]','rb')
f2=open('[Link]','wb')
try:
while True:
d=[Link](f1)
if d['Percentage']>85:
[Link](d,f2)
print(d)
except EOFError:
[Link]()
[Link]()
copy()

Output:-

Enter admission number: 1


Enter name: Ajay
Enter percentage: 96
Do you want to continue? y
Enter admission number: 2
Enter name: Behag
Enter percentage: 78
Do you want to continue? y
Enter admission number: 3
Enter name: Charan
Enter percentage: 98
Do you want to continue? y
Enter admission number: 4
Enter name: Drake
Enter percentage: 56
Do you want to continue? n
{'Admission Number': 1, 'Name': 'Ajay',
'Percentage': 96.0}
{'Admission Number': 3, 'Name': 'Charan',
'Percentage': 98.0}
21)Aim:- Create a CSV file “[Link]” with the following data:
[Eid, Ename, Salary]​

Source Code:-

import csv
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["EId", "Ename", "Salary"])
while True:
id = int(input("Enter an id: "))
name = input("Enter a name: ")
salary = int(input("Enter a salary: "))
[Link]([id, name, salary])
ch = input("Continue? (Y/N)")
if [Link]()=="N":
print("Exitted")
break
elif [Link]()=="Y":
continue
else:
print("INVALID")
with open("[Link]", "r", newline="") as f:
reader = [Link](f)
header = next(reader)
print("ID\tNAME\tSALARY")
for row in reader:
print(row[0], "\t", row[1], "\t", row[2])
Output:-
Enter an id: 101
Enter a name: Ajay
Enter a salary: 7000
Continue? (Y/N) y
Enter an id: 102
Enter a name: Suresh
Enter a salary: 60000
Continue? (Y/N) y
Enter an id: 103
Enter a name: Charan
Enter a salary: 75000
Continue? (Y/N) n
Exitted
ID​ NAME​ SALARY
101​Ajay​ 7000
102​Suresh​ 60000
103​Charan​ 75000
22)Aim:- Write a function to add 2 more records into “[Link]​

Source Code:-

import csv
def add2():
with open("[Link]", "a", newline="") as f:
writer = [Link](f)
for i in range(2):
id = int(input("Enter an id: "))
name = input("Enter a name: ")
salary = int(input("Enter a salary:
"))
[Link]([id, name, salary])
def readData():
with open("[Link]", "r", newline="") as f:
reader = [Link](f)
header = next(reader)
print("ID\tNAME\tSALARY")
for row in reader:
print(row[0], "\t", row[1], "\t",
row[2])
add2()
readData()
Output:-
Enter an id: 201
Enter a name: Dhruv
Enter a salary: 82000
Enter an id: 202
Enter a name: Ram
Enter a salary: 56000
ID​ NAME​ SALARY
101​Ajay​ 7000
102​Suresh​ 60000
103​Charan​ 75000
201​Dhruv​ 82000
202​Ram​ 56000
23)Aim:- Write a function to search if an employee is present or not
by using Eid​

Source Code:-

import csv
def search():
s_id = input("Enter Employee ID to search: ")
flag = False
with open("[Link]", "r", newline="") as f:
reader = [Link](f)
header = next(reader)
for row in reader:
if row[0] == s_id:
print("ID:", row[0])
print("Name:", row[1])
print("Salary:", row[2])
flag = True
break
if not flag:
print("Not Found”)
search()

Output:-
Enter Employee ID to search: 102
ID: 102
Name: Suresh
Salary: 60000

Enter Employee ID to search: 999
Not Found
24)Aim:- Write a function to count and display the total number
of employees whose salary is below 8000​

Source Code:-

import csv
def count():
c = 0
print("ID\tNAME\tSALARY")
with open("[Link]", "r", newline="") as f:
reader = [Link](f)
header = next(reader)
for row in reader:
salary = int(row[2])
if salary < 8000:
print(row[0], "\t", row[1], "\t",
row[2])
c += 1
print("Employees with salary below 8000:", c)

count()

Output:-
ID​ NAME​ SALARY
101​ Ajay​ 7000
Employees with salary below 8000: 1
25)Aim:- Write a function to display those employees whose
name starts with ‘S’​

Source Code:-

import csv
def startingWithS():
print("ID\tNAME\tSALARY")
with open("[Link]", "r", newline="") as f:
reader = [Link](f)
header = next(reader)
for row in reader:
name = row[1]
if [Link]().startswith('s'):
print(row[0], "\t", row[1], "\t",
row[2])
startingWithS()

Output:-
ID​ NAME SALARY
102​Suresh 60000
26)Aim:- Write a function to copy those records whose Eid is
between 101 and 201 ,form “[Link]” to
“[Link]”​

Source Code:-

import csv
def copy():
temp_records = []
with open("[Link]", "r", newline="") as source:
reader = [Link](source)
header = next(reader)
temp_records.append(header)
for row in reader:
eid = int(row[0])
if 101 <= eid <= 201:
temp_records.append(row)
with open("[Link]", "w", newline="") as
target:
writer = [Link](target)
[Link](temp_records)
def show_emp():
print("Contents of [Link]:")
print("ID\tNAME\tSALARY")
with open("[Link]", "r", newline="") as f:
reader = [Link](f)
header = next(reader)
for row in reader:
print(row[0], "\t", row[1], "\t", row[2])​
def show_newemp():
print("Contents of [Link]:")
print("ID\tNAME\tSALARY")
with open("[Link]", "r", newline="") as f:
reader = [Link](f)
header = next(reader)
for row in reader:
print(row[0], "\t", row[1], "\t", row[2])​
show_emp()
copy()
show_newemp()

Output:-

Contents of [Link]:
ID​ NAME​ SALARY
101 ​Ajay ​ 7000
102 ​Suresh ​ 60000
103 ​Charan ​ 75000
201 ​Dhruv ​ 82000
202 ​Ram ​56000
Contents of [Link]:
ID​ NAME ​ SALARY
101 ​Ajay ​ 7000
102 ​Suresh ​ 60000
103 ​Charan ​ 75000
201 ​Dhruv ​ 82000
27)Aim:- Write a program to implement a stack for these
book-details [bookno, book name]. That is, now each item node
of the stack contains two types of information – a bookno and
its name and implement the stack operations
[Link]
[Link]
[Link]
[Link]

Source code:-

stack = []
print("MENU")
print("1. Push element")
print("2. Pop top element")
print("3. View top element")
print("4. Display Stack")
print("5. Exit")

def push(bn, name):


[Link]([bn, name])
def pop():
if len(stack)==0:
return "Underflow error"
else:
return [Link](), "removed"
def peek():
if len(stack)==0:
return "Underflow error"
else:
return stack[-1]
def display():
if len(stack)==0:
print("Empty stack")
else:
for i in range(len(stack)-1, -1, -1):
print(stack[i])
while True:
c = int(input("Enter a choice: "))
if c==1:
bn = int(input("Enter book number: "))
name = input("Enter book name: ")
push(bn, name)
elif c==2:
print(pop())
elif c==3:
print(peek())
elif c==4:
display()
elif c==5:
print("Exitted")
break
else:
print("INVALID")

Output:-
MENU
1. Push element
2. Pop top element
3. View top element
4. Display Stack
5. Exit
Enter a choice: 1
Enter book number: 1
Enter book name: abc
Enter a choice: 1
Enter book number: 2
Enter book name: xyz
Enter a choice: 4
[2, 'xyz']
[1, 'abc']
Enter a choice: 3
[2, 'xyz']
Enter a choice: 2
([2, 'xyz'], 'removed')
Enter a choice: 4
[1, 'abc']
Enter a choice: 6
INVALID
Enter a choice: 5
Exitted
28)Aim:- Mohammed has created a dictionary containing
names and marks of computer science as key,value pairs of 5
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 (CS marks)
are more than or equal to 90 .
● Pop and display the content of the stack,if the stack is
empty display the message as “UNDER FLOW”.

For eg: If the sample content of the dictionary is as follows:

CS={"Raju":80, "Balu":91, "Vishwa":95, Moni":80,


“Govind":90}

The output from the program should be:


Balu Vishwa Govind

The pop operation must display

Govind
vishwa
Balu
UNDER FLOW
Source Code:-

def push_90(st):
for i in CS:
if CS[i]>=90:
[Link](i)
return st

def pop():
while len(stack)!=0:
print([Link]())
else:
print("UNDERFLOW")
stack=[]
CS={"Raju":80, "Balu":91,
"Vishwa":95,"Moni":80,"Govind":90}
print(push_90(stack))
pop()

Output:-​

['Balu', 'Vishwa', 'Govind']
Govind
Vishwa
Balu
UNDERFLOW
28)Aim:- Vedika has created a dictionary containing names and
marks as key-value pairs of 5 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 70.
Pop and display the content of the stack.

The dictionary should be as follows:

d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60,


“Ishika”:95}

Then the output will be: Ishika Vishal Umesh


Source Code:-

def push_70(st):
for i in d:
if d[i] > 70:
[Link](i)
return st
def pop():
while len(stack) != 0:
print([Link](), end=' ')

stack = []
d = {“Ramesh": 58, ”Umesh": 78, “Vishal": 90,
“Khushi": 60, “Ishika": 95}

print(push_70(stack))
pop()

Output:-​

['Umesh', 'Vishal', 'Ishika']
Ishika Vishal Umesh

You might also like