Output:
1. Assignments to perform various number operations such as:
a. Find maximum number from a list of numbers.
def find_maximum(numbers):
maximum = numbers[0]
for number in numbers:
if number > maximum:
maximum = number
return maximum
values = [15, 3, 27, 9, 42]
print("Maximum number is:", find_maximum(values))
b. GCD of two number.
import math
first = 36
second = 60
print("GCD is:", math.gcd(first, second))
c. Square root of a number.
import math
number = 49
print("Square root is:", math.sqrt(number))
d. Check number is prime or not.
def is_prime(number):
if number <= 1:
return False
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
return False
return True
print("Is prime:", is_prime(37))
e. Print first N prime numbers.
def generate_primes(count):
primes = []
number = 2
while len(primes) < count:
if is_prime(number):
primes.append(number)
number += 1
return primes
print("First 10 prime numbers are:", generate_primes(10))
f. Print the Fibonacci series.
def generate_fibonacci(terms):
sequence = [0, 1]
while len(sequence) < terms:
next_value = sequence[-1] + sequence[-2]
sequence.append(next_value)
return sequence[:terms]
print("Fibonacci series is:", generate_fibonacci(10))
Output:
2. Write a program to perform various operations on Strings like creation,
deletion, concatenation.
# String creation
string = "Hello"
print("Created string:", string)
# Concatenation with another string
string = string + " World"
print("After concatenation:", string)
# Accessing part of the string (slicing)
print("First 5 characters:", string[:5])
# Converting to uppercase
string = string.upper()
print("Uppercase string:", string)
# Replacing a word in the string
string = string.replace("HELLO", "HI")
print("After replacement:", string)
# Deleting the string
del string
Output:
3. Create a List L = [take a list of various numbers]. Write programs to
perform following operations on the created list:
L = [3, 8, 15, 22, 30, 41, 50]
print("Original List L:", L)
a. Insert new numbers to list L.
L.append(60)
L.insert(3, 18)
print("After Insertion:", L)
b. Delete numbers from list L.
L.remove(22)
del L[0]
print("After Deletion:", L)
c. Sum all numbers in list L.
sum = 0
for num in L:
sum += num
print("Sum:", sum)
d. Function of Prime:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
e. Sum all prime numbers in list L.
prime_total = 0
for num in L:
if is_prime(num):
prime_total += num
print("Sum of primes:", prime_total)
f. Sum all non-prime numbers in List L.
non_prime_total = 0
for num in L:
if not is_prime(num):
non_prime_total += num
print("Sum of non-primes:", non_prime_total)
g. Delete the list L.
del L
print("List L has been deleted.")
Output:
4. Create a Dictionary D= {‘Name:’ ‘Your Name’, ‘Branch:’ ‘Age’: 20, 20,
10.534}. Write programs to perform following operations:
D={
'Name': 'Yogesh',
'Branch': 'CSE',
'Age': 20,
20: 10.534
}
a. Insert new entry in D.
D['College'] = 'GJU'
print("After Insertion:", D)
b. Delete an entry from D.
del D['Branch']
print("After Deletion:", D)
c. Check whether a key present in D.
key = 'Age'
if key in D:
print(f"Key '{key}' is present in the dictionary.")
else:
print(f"Key '{key}' is NOT present in the dictionary.")
d. Update the value of a key.
D[key] = 21
print("After Updating 'Age':", D)
e. Clear dictionary D.
D.clear()
print("After Clearing:", D)
Output:
5. Write a program on Sets to perform various operation like union,
intersection, difference etc.
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 60, 70, 80}
# Union
union_set = set1 | set2
print("Union of set1 and set2:", union_set)
# Intersection
intersection_set = set1 & set2
print("Intersection of set1 and set2:", intersection_set)
# Difference
difference_set = set1 - set2
print("Difference of set1 and set2 (set1 - set2):", difference_set)
# Symmetric Difference
symmetric_difference_set = set1 ^ set2
print("Symmetric Difference of set1 and set2:", symmetric_difference_set)
Output:
6. Write a program to perform linear search.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
arr = [5, 2, 9, 1, 5, 6]
target = 9
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
7. Write a program to perform binary search.
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
arr = [1, 2, 5, 6, 9]
target = 5
result = binary_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
8. Write a program to perform bubble sort.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)
Output:
9. Write a program to perform selection sort.
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
arr = [64, 25, 12, 22, 11]
selection_sort(arr)
print("Sorted array:", arr)
Output:
10. Write a program to perform insertion sort.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [64, 25, 12, 22, 11]
insertion_sort(arr)
print("Sorted array:", arr)
Output:
11. Write a program to perform quick sort.
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
arr = [64, 25, 12, 22, 11]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)
Output:
12. Write a program to implement and demonstrate the functions of a
simple calculator.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Error! Division by zero."
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input!")
calculator()
Output:
13. Write a program to perform file handling that how data is read and
written to a file and various file handling operations.
# Writing to a file
def write_to_file(filename, data):
with open(filename, 'w') as file:
file.write(data)
print("Data written to file successfully.")
# Appending to a file
def append_to_file(filename, data):
with open(filename, 'a') as file:
file.write(data)
print("Data appended to file successfully.")
# Reading from a file
def read_from_file(filename):
with open(filename, 'r') as file:
content = file.read()
print("Data read from file:")
print(content)
# Checking if a file exists
def file_exists(filename):
try:
with open(filename, 'r') as file:
return True
except FileNotFoundError:
return False
filename = "sample.txt"
# Write data to the file
data_to_write = "Hello, this is a test file.\nWelcome to file handling in Python."
write_to_file(filename, data_to_write)
# Append data to the file
data_to_append = "\nThis is additional data appended to the file."
append_to_file(filename, data_to_append)
# Read data from the file
if file_exists(filename):
read_from_file(filename)
else:
print("File not found.")
Output:
14. Write a program to implement object oriented concept such as classes,
objects, inheritance, and polymorphism.
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
# Derived class (Inheritance)
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
print(f"{self.name} barks.")
# Another derived class (Inheritance)
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def speak(self):
print(f"{self.name} meows.")
# Polymorphism in action
def animal_speak(animal):
animal.speak()
# Creating objects
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "White")
# Calling methods (Polymorphism)
animal_speak(dog)
animal_speak(cat)
# Creating object of base class
animal = Animal("Generic Animal")
animal_speak(animal)
Output:
15. Write a program to perform exception handling.
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result is:", result)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter a valid number.")
finally:
print("Program finished.")
Output:
16. Write a program on usage of package such as Numpy, Pandas.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# New Dictionary with car brands data
car_brands = {
'Brand': ['Toyota', 'Ford', 'BMW', 'Tesla', 'Honda'],
'Sales': [1050000, 850000, 600000, 500000, 750000],
'Revenue (in Billion)': [275, 155, 110, 60, 150],
'Average Price (in $)': [28000, 27000, 50000, 55000, 23000]
}
# DataFrame
df = pd.DataFrame(car_brands)
print("Car Brand Stats:\n")
print(df)
# NumPy to calculate Revenue per Sale
df['RevenuePerSale'] = np.round(df['Revenue (in Billion)'] * 1e9 / df['Sales'], 2)
# Filter brands with RevenuePerSale > 100,000
high_revenue_per_sale = df[df['RevenuePerSale'] > 100000]
print("\nCar Brands with Revenue per Sale > $100,000:\n")
print(high_revenue_per_sale[['Brand', 'RevenuePerSale']])
# Visualization: Bar chart of Sales and Average Price of the car brands
plt.figure(figsize=(10, 6))
plt.bar(df['Brand'], df['Sales'], color='blue', alpha=0.7, label='Sales')
plt.xlabel('Car Brands')
plt.ylabel('Sales (in units)')
plt.title('Sales of Car Brands')
# Adding a second y-axis for Average Price
plt.twinx()
plt.plot(df['Brand'], df['Average Price (in $)'], color='green', marker='o', label='Average Price')
plt.ylabel('Average Price (in $)', color='green')
plt.legend(loc='upper left')
plt.show()