Python 46
Python 46
# String creation
string = "Hello"
print("Created string:", string)
# Converting to uppercase
string = string.upper()
print("Uppercase string:", string)
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)
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.
# 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.
arr = [5, 2, 9, 1, 5, 6]
target = 9
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
7. Write a program to perform binary search.
arr = [1, 2, 5, 6, 9]
target = 5
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]
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]
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
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)
# 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.")
filename = "sample.txt"
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
def speak(self):
print(f"{self.name} barks.")
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")
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
# DataFrame
df = pd.DataFrame(car_brands)
print("Car Brand Stats:\n")
print(df)
# 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')
plt.legend(loc='upper left')
plt.show()