Python lab 26-05

students = [
{“name”: “Alice”, “age”: 20, “grades”: [85, 90, 78]},
{“name”: “Bob”, “age”: 22, “grades”: [60, 75, 58]},
{“name”: “Charlie”, “age”: 21, “grades”: [92, 88, 95]}
]
def calculate_average(grades):
return sum(grades) / len(grades)
def evaluate_student(average):
return “Pass” if average >= 60 else “Fail”
for student in students:
name = student[“name”]
age = student[“age”]
avg_grade = calculate_average(student[“grades”])
status = evaluate_student(avg_grade)
result = f"Student: {name}, Age: {age}, Average Grade: {avg_grade:.2f}, Status: {status}"
print(result)

def pattern_without_regex(text, pattern):
found = False
for i in range(len(text) - len(pattern) + 1):
if text[i:i+len(pattern)] == pattern:
found = True
print(f"Pattern ‘{pattern}’ found at index {i}“)
if not found:
print(f"Pattern ‘{pattern}’ not found”)
import re
def pattern_with_regex(text, pattern):
matches = re.finditer(pattern, text)
found = False
for match in matches:
found = True
print(f"Pattern ‘{pattern}’ found at index {match.start()}“)
if not found:
print(f"Pattern ‘{pattern}’ not found”)
text =input(“Enter the text: “)
pattern =input(“Enter the pattern to search: “)
print(”\nPattern Recognition Without Using Regular Expressions:”)
pattern_without_regex(text, pattern)
print(”\nPattern Recognition Using Regular Expressions:”)
pattern_with_regex(text, pattern)

import os
def write_to_file(filename, content):
with open(filename, ‘w’) as file:
file.write(content)
print(f"Data written to {filename}“)
def read_from_file(filename):
try:
with open(filename, ‘r’) as file:
content = file.read()
print(f"Content of {filename}:”)
print(content)
except FileNotFoundError:
print(f"Error: {filename} not found!“)
def organize_files(folder_name, file_list):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
for file in file_list:
if os.path.exists(file):
os.rename(file, os.path.join(folder_name, file))
print(f"Moved {file} to {folder_name}/”)
filename = “sample.txt”
content = “Hello, this is a sample file demonstrating file operations in Python.”
write_to_file(filename, content)
read_from_file(filename)
folder = “Organized_Files”
organize_files(folder, [filename])

class Student:
def init(self, name, student_id):
self.name = name
self.student_id = student_id
def display_info(self):
print (f"Name: {self.name}“)
print (f"Student ID: {self.student_id}”)
def study(self):
print(f"{self.name} is studying.“)
class GraduateStudent(Student):
def init(self, name, student_id, thesis_title):
super().init(name, student_id)
self.thesis_title = thesis_title
def display_info(self):
super().display_info()
print(f"Thesis Title: {self.thesis_title}”)
def research(self):
print(f"{self.name} is researching on ‘{self.thesis_title}’.“)
student1 = Student(“Alice”, “S1001”)
grad_student1 = GraduateStudent(“Bob”, “G2001”, “AI in Healthcare”)
print(”=== Student Info ===“)
student1.display_info()
student1.study()
print(”\n=== Graduate Student Info ===")
grad_student1.display_info()
grad_student1.study()
grad_student1.research()

num = 42
name = “Alice”
items = [1, 2, 3]
def show_object_attributes(obj):
print(f"Object: {obj}“)
print(f"Identity (id): {id(obj)}”)
print(f"Type: {type(obj)}“)
print(f"Value: {obj}”)
print(“-” * 40)
show_object_attributes(num)
show_object_attributes(name)
show_object_attributes(items)
print(“Changing value to see if identity changes:”)
num2 = 42
print(f"num id: {id(num)}, num2 id: {id(num2)} (Should be same because integers are immutable and reused)“)
items.append(4)
print(f"After modifying ‘items’:”)
show_object_attributes(items)

class Book:
def init(self, title, author):
self.title = title
self.author = author
print(f"Book ‘{self.title}’ by {self.author} created.“)
def display_info(self):
print(f"Title: {self.title}, Author: {self.author}”)
def delete(self):
print(f"Book ‘{self.title}’ is destroyed (memory freed).“)
class Library:
def init(self):
self.books =
def add_book(self, book):
self.books.append(book)
def remove_book_by_title(self, title):
for book in self.books:
if book.title == title:
self.books.remove(book)
print(f"Book ‘{title}’ removed from library.”)
Book.delete(book)
del book
return
print(f"Book ‘{title}’ not found in library.“)
def show_books(self):
print(”\nBooks in Library:“)
for book in self.books:
book.display_info()
library = Library()
b1 = Book(“The Alchemist”, “Paulo Coelho”)
b2 = Book(“1984”, “George Orwell”)
b3 = Book(“To Kill a Mockingbird”, “Harper Lee”)
library.add_book(b1)
library.add_book(b2)
library.add_book(b3)
library.show_books()
print(”\nDeleting book ‘1984’…“)
library.remove_book_by_title(“1984”)
print(”\nAfter deletion:")
library.show_books()

import requests
import pandas as pd
from bs4 import BeautifulSoup
url = “BBC News - Breaking news, video and the latest top stories from the U.S. and around the world
headers = {“User-Agent”: “Mozilla/5.0”}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, “html.parser”)
headlines =
for a_tag in soup.select(“a[href] h3, a[href] h2”):
headline = a_tag.get_text(strip=True)
parent = a_tag.find_parent(“a”)
if headline and parent and parent.has_attr(“href”):
link = f"https://www.bbc.com{parent[‘href’]}"
headlines.append({“Headline”: headline, “URL”: link})
unique_headlines = {item[“Headline”]: item for item in headlines}.values()
df = pd.DataFrame(unique_headlines)
df.to_excel(“bbc_news_headlines.xlsx”, index=False)
print(f"Scraped {len(df)} headlines and saved to ‘bbc_news_headlines.xlsx’“)
print(”\nTop 5 headlines with links:")
print(df.head())

import pandas as pd
df = pd.read_csv(‘sample_data.csv’)
print(“Original DataFrame:”)
print(df)
print(“\nDescriptive statistics:”)
print(df.describe())
print(“\nFirst 3 rows:”)
print(df.head(3))
print(“\nAll rows using loc[:]:”)
print(df.loc[:])
print(“\nCity value counts:”)
print(df[‘City’].value_counts())
df_no_duplicates = df.drop_duplicates()
print(“\nData after dropping duplicates:”)
print(df_no_duplicates)
df_filled = df.fillna({
‘Name’: ‘Unknown’,
‘Age’: df[‘Age’].mean(),
‘City’: ‘Unknown’
})
print(“\nData after filling missing values:”)
print(df_filled)

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df[‘species’] = pd.Categorical.from_codes(iris.target, iris.target_names)
df.drop(‘species’, axis=1).hist(bins=20, figsize=(10, 7), layout=(2, 2))
plt.suptitle(‘Histograms of Numerical Features’)
plt.show()
sns.countplot(x=‘species’, data=df)
plt.title(‘Species Distribution’)
plt.xlabel(‘Species’)
plt.ylabel(‘Count’)
plt.show()
species_count = df[‘species’].value_counts()
plt.figure(figsize=(6, 6))
plt.pie(species_count, labels=species_count.index, autopct=‘%1.1f%%’, startangle=90, colors=sns.color_palette(“Set2”))
plt.title(‘Species Distribution (Pie Chart)’)
plt.show()
species_avg = df.groupby(‘species’).mean()
species_avg.plot(kind=‘bar’, figsize=(10, 6))
plt.title(‘Average of Numerical Features by Species’)
plt.ylabel(‘Average Value’)
plt.xticks(rotation=0)
plt.show()

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df[‘species’] = pd.Categorical.from_codes(iris.target, iris.target_names)
plt.figure(figsize=(8, 6))
sns.lineplot(x=‘sepal length (cm)’, y=‘sepal width (cm)’, data=df)
plt.title(‘Line Plot: Sepal Length vs Sepal Width’)
plt.xlabel(‘Sepal Length (cm)’)
plt.ylabel(‘Sepal Width (cm)’)
plt.show()
plt.figure(figsize=(8, 6))
sns.scatterplot(x=‘petal length (cm)’, y=‘petal width (cm)’, data=df, hue=‘species’, palette=‘Set1’)
plt.title(‘Scatter Plot: Petal Length vs Petal Width’)
plt.xlabel(‘Petal Length (cm)’)
plt.ylabel(‘Petal Width (cm)’)
plt.legend(title=‘Species’)
plt.show()
correlation_matrix = df.drop(‘species’, axis=1).corr()
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap=‘coolwarm’, fmt=‘.2f’, linewidths=0.5)
plt.title(‘Correlation Matrix of Numerical Features’)
plt.show()
plt.figure(figsize=(8, 6))
sns.regplot(x=‘sepal length (cm)’, y=‘petal length (cm)’, data=df, scatter_kws={‘s’: 50}, line_kws={‘color’: ‘red’})
plt.title(‘Scatter Plot with Regression Line: Sepal Length vs Petal Length’)
plt.xlabel(‘Sepal Length (cm)’)
plt.ylabel(‘Petal Length (cm)’)
plt.show()

Please read Getting good answers to your questions and follow it as a guide to edit this and for making future posts. A lot of that advice is general for such forums.

Plus, please consider if you are posting in an appropriate forum. I see a lot of Python code and this wouldn’t belong here unless you tried running it directly with Python or IPython, the more traditional way, and it didn’t cause whatever issue you think you are seeing that you didn’t tell us about.

If this were an appropriate post what you provided isn’t useable. Please, also learn about how to post code at such sites as this in useable form. To help you with that see about ‘block code formatting’ here. (Or see about ‘fenced code blocks’ here. They are both the same thing if you look into the details.

1 Like