Python Imp 001
Python Imp 001
cat = Cat("Whiskers")
print(cat.speak()) # Meow
Q.3) Find all indices of a substring
python
def find_all_indices(main_string, sub_string):
indices = []
start_index = 0
while True:
index = main_string.find(sub_string, start_index)
if index == -1:
break
indices.append(index)
start_index = index + 1
return indices
# Example usage
text = "hello hello world hello"
print(find_all_indices(text, "hello")) # [0, 6, 18]
Q.4) MongoDB CRUD operations with Python
python
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['example_db']
collection = db['example_collection']
# Create (Insert)
document = {"name": "John", "age": 30, "city": "New York"}
insert_result = collection.insert_one(document)
print("Inserted ID:", insert_result.inserted_id)
# Read (Find)
print("\nAll documents:")
for doc in collection.find():
print(doc)
# Update
update_query = {"name": "John"}
new_values = {"$set": {"age": 31}}
collection.update_one(update_query, new_values)
print("\nAfter update:")
print(collection.find_one({"name": "John"}))
# Delete
delete_query = {"name": "John"}
collection.delete_one(delete_query)
print("\nAfter delete, count:", collection.count_documents({}))
Q.5) File operations
python
# Part a) File modes:
# 'r' - Read (default)
# 'w' - Write (truncates existing file)
# 'a' - Append
# 'x' - Exclusive creation (fails if file exists)
# 'b' - Binary mode
# 't' - Text mode (default)
# '+' - Updating (read/write)
# Appending to a file
with open('example.txt', 'a') as file:
file.write("This line is appended.\n")
Q.6) Lists and List Functions
python
# Lists are ordered, mutable collections of items
my_list = [1, 2, 3, 4]
# Example
text = "hello world python programming"
print(last_char_upper(text)) # hellO worlD pythoN programminG
Q.8) Adding index, row or column to pandas DataFrame
python
import pandas as pd
# Adding a column
df['City'] = ['New York', 'London', 'Paris']
print("After adding column:")
print(df)
# Adding a row
new_row = {'Name': 'Mike', 'Age': 40, 'City': 'Berlin'}
df = df.append(new_row, ignore_index=True)
print("\nAfter adding row:")
print(df)
class Parent2:
def method2(self):
print("Parent2 method")
# Multilevel Inheritance
class Grandparent:
def method(self):
print("Grandparent method")
class Parent(Grandparent):
def method(self):
super().method()
print("Parent method")
class Child(Parent):
def method(self):
super().method()
print("Child method")
# Demonstration
print("Multiple Inheritance:")
c = Child()
c.method1()
c.method2()
c.method3()
print("\nMultilevel Inheritance:")
child = Child()
child.method()
Q.11) NumPy Arrays
python
import numpy as np
# Array of zeros
arr2 = np.zeros((2, 3))
print("\nArray of zeros:")
print(arr2)
# Array of ones
arr3 = np.ones((3, 2))
print("\nArray of ones:")
print(arr3)
# Deleting by index
df_reset = df.reset_index(drop=True)
print("\nAfter resetting index:")
print(df_reset)
Q.13) Creating Pandas DataFrames
python
import pandas as pd
# From a dictionary
data = {'Name': ['John', 'Anna'], 'Age': [28, 24]}
df1 = pd.DataFrame(data)
print("From dictionary:")
print(df1)
Comparison:
python
import re
python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
fibonacci(10) # 0 1 1 2 3 5 8 13 21 34
e) Sum of odd and even numbers
python
def sum_odd_even(n):
odd_sum = 0
even_sum = 0
for i in range(1, n+1):
if i % 2 == 0:
even_sum += i
else:
odd_sum += i
return odd_sum, even_sum
python
def is_leap_year(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
else:
return year % 400 == 0
print(is_leap_year(2000)) # True
print(is_leap_year(1900)) # False
print(is_leap_year(2020)) # True
g) Multithreading
python
import threading
import time
def print_numbers():
for i in range(5):
time.sleep(1)
print(i)
def print_letters():
for letter in 'abcde':
time.sleep(1)
print(letter)
# Create threads
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_letters)
# Start threads
t1.start()
t2.start()
print("Done!")
h) Modules
python
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# main.py
import mymodule
python
def is_palindrome(n):
original = str(n)
reversed_str = original[::-1]
return original == reversed_str
print(is_palindrome(121)) # True
print(is_palindrome(123)) # False
print(is_palindrome("madam")) # True
j) Matrix multiplication
python
def matrix_multiply(a, b):
return [[sum(i*j for i,j in zip(row, col)) for col in zip(*b)] for row in a]
# 2x2 matrices
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(7)) # True
print(is_prime(10)) # False
l) Dictionary operations
python
my_dict = {'name': 'John', 'age': 30}
# Add
my_dict['city'] = 'New York'
print("After add:", my_dict)
# Remove
del my_dict['age']
print("After remove:", my_dict)
# Pop
city = my_dict.pop('city')
print("After pop:", my_dict, "Popped value:", city)
# Update
my_dict.update({'age': 35, 'job': 'Developer'})
print("After update:", my_dict)
Q.7) Short Notes
a) The dir() function
The dir() function returns a list of valid attributes and methods of an object. Without arguments, it re-
turns names in the current local scope.
python
import math
print(dir(math)) # Shows all names in math module
class MyClass:
def __init__(self):
self.x = 10
def method(self):
pass
python
x = 'global' # Global scope
def outer():
x = 'enclosing' # Enclosing scope
def inner():
x = 'local' # Local scope
print(x)
inner()
print(x)
outer()
print(x)
d) Tuples
Tuples are immutable sequences, typically used to store collections of heterogeneous data.
python
# Creating tuples
t1 = (1, 2, 3)
t2 = ('a', 'b', 'c')
t3 = (1,) # Single-element tuple needs a comma
# Accessing elements
print(t1[0]) # 1
a) Lambda Function
python
# Simple lambda
square = lambda x: x**2
print(square(5)) # 25
c) Polymorphism
The ability to present the same interface for different underlying forms.
python
class Dog:
def speak(self):
return "Bark"
class Cat:
def speak(self):
return "Meow"
def animal_sound(animal):
print(animal.speak())
animal_sound(dog) # Bark
animal_sound(cat) # Meow
d) Iterator and Generator
python
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
python
def countdown(n):
while n > 0:
yield n
n -= 1
k) Matplotlib
python
import matplotlib.pyplot as plt
import numpy as np
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.grid(True)
plt.show()
# Bar chart
categories = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(categories, values)
plt.show()
# Scatter plot
x = np.random.rand(50)
y = np.random.rand(50)
plt.scatter(x, y)
plt.show()
l) If-else, for, while
python
# if-elif-else
age = 20
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
# for loop
for i in range(5):
print(i)
# while loop
count = 0
while count < 5:
print(count)
count += 1