0% found this document useful (0 votes)
2 views

Python P

The document contains multiple Python programs demonstrating stack operations using lists and collections.deque, as well as basic DataFrame operations with pandas. It includes programs for storing and searching employee details in a CSV file, counting characters in a text file, and copying lines starting with 'V' to another file. Each section provides code examples and explanations for functionality such as push, pop, peek, and display operations for stacks.

Uploaded by

monkeyduchiha69
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python P

The document contains multiple Python programs demonstrating stack operations using lists and collections.deque, as well as basic DataFrame operations with pandas. It includes programs for storing and searching employee details in a CSV file, counting characters in a text file, and copying lines starting with 'V' to another file. Each section provides code examples and explanations for functionality such as push, pop, peek, and display operations for stacks.

Uploaded by

monkeyduchiha69
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1.

Stack Operations using List


python
CopyEdit
class Stack:
def __init__(self):
self.stack = []

def push(self, item):


"""Push an item onto the stack."""
self.stack.append(item)
print(f"Pushed {item} onto the stack.")

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()

2. Stack Implementation using collections.deque


python
CopyEdit
from collections import deque
stack = deque()

# 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!")

3. DataFrame Program: Basic Operations with pandas


python
CopyEdit
import pandas as pd

# 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)

# Add a new row


new_row = {"Empno": 104, "Name": "Diana", "Salary": 70000}
df = df.append(new_row, ignore_index=True)
print("\nDataFrame after adding a new row:")
print(df)

# Filter DataFrame for employees with Salary > 55000


filtered_df = df[df["Salary"] > 55000]
print("\nEmployees with Salary > 55000:")
print(filtered_df)

# Save DataFrame to CSV


df.to_csv("Employee.csv", index=False)
print("\nDataFrame saved to 'Employee.csv'.")

4. DataFrame Program: Reading and Manipulating Data


python
CopyEdit
import pandas as pd
# Read from a CSV file
df = pd.read_csv("Employee.csv")
print("DataFrame from 'Employee.csv':")
print(df)

# Search for an employee by Empno


empno = int(input("\nEnter Empno to search: "))
result = df[df["Empno"] == empno]
if not result.empty:
print("Employee Found:")
print(result)
else:
print("Empno not found!")

5. Stack Implementation using Class and Exception Handling


python
CopyEdit
class CustomStack:
def __init__(self, max_size=5):
self.stack = []
self.max_size = max_size

def push(self, value):


if len(self.stack) < self.max_size:
self.stack.append(value)
print(f"{value} pushed to stack.")
else:
print("Stack Overflow! Cannot push more elements.")

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

Store employee details in a CSV file and search for an Empno.

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

Copy lines starting with V to another file named Vaasavi.txt.

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()

4. Program: Stack Implementation

Implement a stack using a list with operations: Push, Pop, Display, and Peek.

python
CopyEdit
class Stack:
def __init__(self):
self.stack = []

def push(self, item):


"""Pushes an item onto the stack."""
self.stack.append(item)
print(f"Pushed: {item}")

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.")

You might also like