Python P
Python P
def pop(self):
"""Pop an item from the stack."""
if not self.is_empty():
item = self.stack.pop()
print(f"Popped {item} from the stack.")
else:
print("Stack is empty! Nothing to pop.")
def peek(self):
"""Peek at the top item of the stack."""
if not self.is_empty():
print(f"Top of the stack is: {self.stack[-1]}")
else:
print("Stack is empty!")
def display(self):
"""Display the stack."""
print("Stack:", self.stack)
def is_empty(self):
"""Check if the stack is empty."""
return len(self.stack) == 0
# Main Program
s = Stack()
s.push(10)
s.push(20)
s.display()
s.peek()
s.pop()
s.display()
# Push operation
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack after pushes:", list(stack))
# Pop operation
print("Popped:", stack.pop())
# Peek operation
if stack:
print("Top of the stack:", stack[-1])
else:
print("Stack is empty!")
# Create a DataFrame
data = {
"Empno": [101, 102, 103],
"Name": ["Alice", "Bob", "Charlie"],
"Salary": [50000, 60000, 55000],
}
df = pd.DataFrame(data)
print("Initial DataFrame:")
print(df)
def pop(self):
if self.stack:
return self.stack.pop()
else:
print("Stack Underflow! The stack is empty.")
def peek(self):
if self.stack:
return self.stack[-1]
else:
return "Stack is empty."
def display(self):
print("Current Stack:", self.stack)
# Main Program
cs = CustomStack(max_size=3)
cs.push(5)
cs.push(10)
cs.push(15)
cs.display()
cs.push(20) # Testing overflow
cs.pop()
cs.display()
1. Creating a python program named “Mycsv.py” to store the details of Empno, Name
and Salary in “Emp.csv” and search for an Empno entered by the user. If found, display
the details of the Employee else display Empno is not present.
2. Create a python program named Count.py to read a text file – Mytext.txt and display
the number of vowels/consonants/lower case/ upper case characters.
3. Create a python program named One.py and copy the lines that are starting with ‘V’ in
another file named “Vaasavi.txt”
4. Write a python program using list to implement stack data structure and
perform the following operations: a. Push(), b. Pop(), c. Display() d. Peek()
1. Program: Mycsv.py
python
CopyEdit
import csv
def store_employee_details():
"""Stores employee details in Emp.csv."""
with open("Emp.csv", mode="w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Empno", "Name", "Salary"]) # Writing header
n = int(input("Enter the number of employees: "))
for _ in range(n):
empno = input("Enter Employee Number: ")
name = input("Enter Name: ")
salary = input("Enter Salary: ")
writer.writerow([empno, name, salary])
print("Employee details saved successfully.")
def search_employee():
"""Searches for an employee in Emp.csv by Empno."""
empno_to_search = input("Enter the Employee Number to search: ")
found = False
with open("Emp.csv", mode="r") as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
if row[0] == empno_to_search:
print(f"Employee Found - Empno: {row[0]}, Name: {row[1]},
Salary: {row[2]}")
found = True
break
if not found:
print("Empno is not present.")
# Main Program
store_employee_details()
search_employee()
2. Program: Count.py
Read a text file and display the count of vowels, consonants, lowercase, and uppercase
characters.
python
CopyEdit
def count_characters():
"""Counts vowels, consonants, lowercase, and uppercase characters in
Mytext.txt."""
try:
with open("Mytext.txt", mode="r") as file:
text = file.read()
vowels = "aeiouAEIOU"
vowel_count = sum(1 for char in text if char in vowels)
consonant_count = sum(1 for char in text if char.isalpha() and
char not in vowels)
lower_case_count = sum(1 for char in text if char.islower())
upper_case_count = sum(1 for char in text if char.isupper())
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")
print(f"Lowercase Characters: {lower_case_count}")
print(f"Uppercase Characters: {upper_case_count}")
except FileNotFoundError:
print("The file Mytext.txt does not exist.")
# Main Program
count_characters()
3. Program: One.py
python
CopyEdit
def copy_lines_starting_with_v():
"""Copies lines starting with 'V' to Vaasavi.txt."""
try:
with open("Mytext.txt", mode="r") as infile, open("Vaasavi.txt",
mode="w") as outfile:
for line in infile:
if line.startswith("V"):
outfile.write(line)
print("Lines starting with 'V' have been copied to Vaasavi.txt.")
except FileNotFoundError:
print("The file Mytext.txt does not exist.")
# Main Program
copy_lines_starting_with_v()
Implement a stack using a list with operations: Push, Pop, Display, and Peek.
python
CopyEdit
class Stack:
def __init__(self):
self.stack = []
def pop(self):
"""Pops the top item from the stack."""
if self.is_empty():
print("Stack is empty. Cannot pop.")
else:
print(f"Popped: {self.stack.pop()}")
def display(self):
"""Displays the stack."""
if self.is_empty():
print("Stack is empty.")
else:
print("Stack elements:", self.stack)
def peek(self):
"""Displays the top item of the stack."""
if self.is_empty():
print("Stack is empty.")
else:
print(f"Top element: {self.stack[-1]}")
def is_empty(self):
"""Checks if the stack is empty."""
return len(self.stack) == 0
# Main Program
stack = Stack()
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Peek")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
element = input("Enter the element to push: ")
stack.push(element)
elif choice == 2:
stack.pop()
elif choice == 3:
stack.display()
elif choice == 4:
stack.peek()
elif choice == 5:
print("Exiting program.")
break
else:
print("Invalid choice. Try again.")