Python Programming:: Class: II B.Tech(AI&DS), 1-Semester {2025-26}
Syllabus | Lesson Plans | Materials | Quiz | Assignments | Mid Papers
Files:-
Python
import numpy as np
# 1. Sort words in a file
def sort_words_in_file(input_file, output_file):
"""
Reads words from an input file, sorts them in lowercase, and writes
the sorted words to an output file.
"""
try:
with open(input_file, 'r') as infile:
words = infile.read().split()
# Convert to lowercase and sort
sorted_words = sorted([word.lower() for word in words])
with open(output_file, 'w') as outfile:
for word in sorted_words:
outfile.write(word + '\n')
print(f"Words from '{input_file}' have been sorted and saved to '{output_file}'.")
except FileNotFoundError:
print("Error: The input file was not found.")
# 2. Print each line of a file in reverse order
def reverse_lines_in_file(filename):
"""
Reads a file and prints each line in reverse order.
"""
try:
with open(filename, 'r') as file:
for line in file:
print(line.strip()[::-1])
except FileNotFoundError:
print("Error: The file was not found.")
# 3. Compute characters, words, and lines in a file
def file_stats(filename):
"""
Computes and prints the number of characters, words, and lines in a file.
"""
try:
with open(filename, 'r') as file:
content = file.read()
num_chars = len(content)
num_words = len(content.split())
num_lines = content.count('\n') + 1 if content else 0
print(f"File: {filename}")
print(f"Characters: {num_chars}")
print(f"Words: {num_words}")
print(f"Lines: {num_lines}")
except FileNotFoundError:
print("Error: The file was not found.")
# 4. Array operations
def array_operations():
"""
Demonstrates creating, displaying, appending, inserting, and reversing
the order of items in a Python list (used as an array).
"""
arr = [10, 20, 30, 40]
print(f"Original array: {arr}")
# Append
arr.append(50)
print(f"After appending 50: {arr}")
# Insert
arr.insert(1, 15)
print(f"After inserting 15 at index 1: {arr}")
# Reverse
arr.reverse()
print(f"After reversing the array: {arr}")
# 5. Matrix operations
def matrix_operations():
"""
Demonstrates adding, transposing, and multiplying two matrices using NumPy.
"""
# Create two matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print("Matrix A:\n", A)
print("Matrix B:\n", B)
# Addition
sum_matrix = A + B
print("\nMatrix Addition (A + B):\n", sum_matrix)
# Transpose
transpose_A = A.T
print("\nTranspose of A:\n", transpose_A)
# Multiplication
product_matrix = np.dot(A, B)
print("\nMatrix Multiplication (A * B):\n", product_matrix)
# 6. Shape Class and Subclasses
import math
class Shape:
"""Base class for a geometric shape."""
def __init__(self, name):
self.name = name
def area(self):
"""Calculates the area of the shape."""
raise NotImplementedError("Subclass must implement abstract method.")
def perimeter(self):
"""Calculates the perimeter of the shape."""
raise NotImplementedError("Subclass must implement abstract method.")
class Circle(Shape):
"""Subclass for a circle."""
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
class Triangle(Shape):
"""Subclass for a triangle."""
def __init__(self, side1, side2, side3):
super().__init__("Triangle")
self.sides = [side1, side2, side3]
def area(self):
s = self.perimeter() / 2
return math.sqrt(s * (s - self.sides[0]) * (s - self.sides[1]) * (s - self.sides[2]))
def perimeter(self):
return sum(self.sides)
class Square(Shape):
"""Subclass for a square."""
def __init__(self, side):
super().__init__("Square")
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
# Example usage of the Shape classes
def shape_class_example():
"""
Creates instances of the shape classes and demonstrates their methods.
"""
circle = Circle(5)
print(f"Circle area: {circle.area():.2f}")
print(f"Circle perimeter: {circle.perimeter():.2f}")
triangle = Triangle(3, 4, 5)
print(f"Triangle area: {triangle.area():.2f}")
print(f"Triangle perimeter: {triangle.perimeter():.2f}")
square = Square(6)
print(f"Square area: {square.area():.2f}")
print(f"Square perimeter: {square.perimeter():.2f}")
This program shows how to merge two dictionaries. We'll use the | operator, available in Python 3.9 and later, for a concise way to combine them. For older versions, the ** operator within a new dictionary is a common method.
# Program to merge two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Python 3.9+ method
merged_dict = dict1 | dict2
print(f"Merged Dictionary (Python 3.9+): {merged_dict}")
# Older Python version method
merged_dict_old = {**dict1, **dict2}
print(f"Merged Dictionary (Older versions): {merged_dict_old}")
This program counts the frequency of each element in a list and then finds the element with the highest frequency using a dictionary.
# Program to find the most frequent element in a list
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
# Use Counter to get frequencies
frequency_dict = Counter(my_list)
print(f"Frequency Dictionary: {frequency_dict}")
# Find the most common element
most_common = frequency_dict.most_common(1)[0]
print(f"Most frequent element: '{most_common[0]}' with count {most_common[1]}")
This example demonstrates how to swap keys and values of a dictionary. This is useful for creating a reverse lookup structure. Note that this might lead to data loss if the original values are not unique.
# Program to invert a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Use a dictionary comprehension for a concise inversion
inverted_dict = {value: key for key, value in my_dict.items()}
print(f"Original Dictionary: {my_dict}")
print(f"Inverted Dictionary: {inverted_dict}")
Here's how to process a list of dictionaries and group them based on a common key. This is a common task when working with structured data.
# Program to group a list of dictionaries by a key
from collections import defaultdict
data = [
{'name': 'Alice', 'city': 'New York'},
{'name': 'Bob', 'city': 'London'},
{'name': 'Charlie', 'city': 'New York'},
{'name': 'David', 'city': 'London'},
]
grouped_by_city = defaultdict(list)
for item in data:
grouped_by_city[item['city']].append(item['name'])
print(f"Grouped by city: {dict(grouped_by_city)}")
This program shows how to create a new dictionary containing only the key-value pairs that satisfy a specific condition. Dictionary comprehensions are ideal for this.
# Program to filter a dictionary
my_dict = {'a': 10, 'b': 25, 'c': 5, 'd': 30}
# Filter to keep only items where the value is greater than 15
filtered_dict = {key: value for key, value in my_dict.items() if value > 15}
print(f"Original Dictionary: {my_dict}")
print(f"Filtered Dictionary: {filtered_dict}")
This example demonstrates how to combine values from multiple dictionaries if they share a common key. Here, we'll sum the values.
# Program to combine values from multiple dictionaries
from collections import defaultdict
dict1 = {'a': 10, 'b': 20}
dict2 = {'b': 30, 'c': 40}
dict3 = {'a': 50, 'c': 60}
combined_dict = defaultdict(int)
for d in [dict1, dict2, dict3]:
for key, value in d.items():
combined_dict[key] += value
print(f"Combined Dictionary: {dict(combined_dict)}")
While dictionaries themselves are not ordered (pre-Python 3.7), we can get a sorted list of their items. This program sorts a dictionary by its values in descending order.
# Program to sort a dictionary by its values
my_dict = {'a': 10, 'b': 5, 'c': 20}
# Get a sorted list of key-value pairs
sorted_items = sorted(my_dict.items(), key=lambda item: item[1], reverse=True)
# Create a new dictionary from the sorted list
sorted_dict = dict(sorted_items)
print(f"Original Dictionary: {my_dict}")
print(f"Sorted Dictionary (by value): {sorted_dict}")
This program shows how to perform an operation on the values of a dictionary, such as squaring each value. This can be done efficiently with a dictionary comprehension.
# Program to perform element-wise operations on values
my_dict = {'a': 2, 'b': 3, 'c': 4}
# Create a new dictionary with squared values
squared_dict = {key: value ** 2 for key, value in my_dict.items()}
print(f"Original Dictionary: {my_dict}")
print(f"Dictionary with squared values: {squared_dict}")
This example demonstrates how to access and modify values within a nested dictionary structure.
# Program for nested dictionary operations
nested_dict = {
'user1': {'name': 'Alice', 'age': 30},
'user2': {'name': 'Bob', 'age': 25}
}
# Access a nested value
print(f"User 1's age: {nested_dict['user1']['age']}")
# Modify a nested value
nested_dict['user2']['age'] = 26
print(f"Modified User 2's age: {nested_dict['user2']['age']}")
# Add a new key-value pair to a nested dictionary
nested_dict['user1']['city'] = 'London'
print(f"Updated User 1 data: {nested_dict['user1']}")
This program takes a nested dictionary and flattens it into a single-level dictionary. This is a more advanced task requiring recursion or iteration.
# Program to flatten a nested dictionary
def flatten_dict(d, parent_key='', sep='_'):
""" Flattens a nested dictionary. """
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
nested_dict = {
'a': 1,
'b': {
'c': 2,
'd': {
'e': 3,
'f': 4
}
}
}
flattened_dict = flatten_dict(nested_dict)
print(f"Flattened Dictionary: {flattened_dict}")
Syllabus | Lesson Plans | Materials | Quiz | Assignments | Mid Papers