1.
if __name__ == '__main__':
N = int(input().strip())
result = []
for _ in range(N):
command = input().strip().split()
if command[0] == "insert":
result.insert(int(command[1]), int(command[2]))
elif command[0] == "print":
print(result)
elif command[0] == "remove":
result.remove(int(command[1]))
elif command[0] == "append":
result.append(int(command[1]))
elif command[0] == "sort":
result.sort()
elif command[0] == "pop":
result.pop()
elif command[0] == "reverse":
result.reverse()
2.
def nth_term_of_series(n):
if n % 2 == 0:
# Even terms: 2^(n/2 - 1)
return 2 ** (n // 2 - 1)
else:
# Odd terms: n/2
return 3 ** (n // 2)
# Test the function
n = int(input("Enter the value of n: "))
result = nth_term_of_series(n)
print("The", n, "th term of the series is:", result)
3.
def custom_sort(lst):
# Split the list into two sublists: odd indices and even indices
odd_indices = lst[1::2]
even_indices = lst[::2]
# Sort the sublists separately
odd_indices.sort()
even_indices.sort(reverse=True)
# Combine the sorted sublists back into a single list
result = []
for i in range(len(lst)):
if i % 2 == 0:
result.append(even_indices.pop(0))
else:
result.append(odd_indices.pop(0))
return result
# Test the function
sample_input = [5, 3, 2, 1, 4, 6, 7, 9]
output = custom_sort(sample_input)
print("Expected Output:", output)
4.
def decrypt_message(encrypted_message):
decrypted_message = ""
for char in encrypted_message:
# Decrypt uppercase letters
if char.isupper():
decrypted_char = chr(((ord(char) - 65 - 3) % 26) + 65)
decrypted_message += decrypted_char
else:
decrypted_message += char # Keep non-alphabetic characters unchanged
return decrypted_message
# Test cases
input1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
input2 = "ATTACKATONCE"
print("Output 1:", decrypt_message(input1))
print("Output 2:", decrypt_message(input2))
5.
def power(base, exponent):
if exponent == 0:
return 1
elif exponent < 0:
return 1 / power(base, -exponent)
else:
return base * power(base, exponent - 1)
# Input base and exponent from the user
base = float(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
# Compute and print the result using the recursive function
result = power(base, exponent)
print("Result:", result)
6.
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def celsius_to_kelvin(celsius):
return celsius + 273.15
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
def fahrenheit_to_kelvin(fahrenheit):
return (fahrenheit - 32) * 5/9 + 273.15
def kelvin_to_celsius(kelvin):
return kelvin - 273.15
def kelvin_to_fahrenheit(kelvin):
return (kelvin - 273.15) * 9/5 + 32
import temperature_converter
# Convert Celsius to Fahrenheit and Kelvin
celsius = 25
fahrenheit = temperature_converter.celsius_to_fahrenheit(celsius)
kelvin = temperature_converter.celsius_to_kelvin(celsius)
print(f"{celsius} Celsius is equal to {fahrenheit:.2f} Fahrenheit")
print(f"{celsius} Celsius is equal to {kelvin:.2f} Kelvin")
# Convert Fahrenheit to Celsius and Kelvin
fahrenheit = 77
celsius = temperature_converter.fahrenheit_to_celsius(fahrenheit)
kelvin = temperature_converter.fahrenheit_to_kelvin(fahrenheit)
print(f"{fahrenheit} Fahrenheit is equal to {celsius:.2f} Celsius")
print(f"{fahrenheit} Fahrenheit is equal to {kelvin:.2f} Kelvin")
# Convert Kelvin to Celsius and Fahrenheit
kelvin = 298
celsius = temperature_converter.kelvin_to_celsius(kelvin)
fahrenheit = temperature_converter.kelvin_to_fahrenheit(kelvin)
print(f"{kelvin} Kelvin is equal to {celsius:.2f} Celsius")
print(f"{kelvin} Kelvin is equal to {fahrenheit:.2f} Fahrenheit")
7.
# Initialize the answer key
answer_key = ['A', 'B', 'C', 'A']
def evaluate_responses(student_responses):
marks = 0
for i in range(len(answer_key)):
if student_responses[i] == answer_key[i]:
marks += 10
return marks
# Read and evaluate responses for each student
for i in range(1, 6):
print(f"Enter responses for Student {i}:")
student_responses = []
for j in range(4):
response = input(f"Response for question {j+1} (A/B/C): ").upper()
student_responses.append(response)
student_marks = evaluate_responses(student_responses)
print(f"Student {i} obtained {student_marks} marks.\n")
8.
class FlightBookingSystem:
def __init__(self):
self.flights = {}
def add_flight(self, flight_id, departure_city, arrival_city, departure_time, available_seats):
self.flights[flight_id] = {
'departure_city': departure_city,
'arrival_city': arrival_city,
'departure_time': departure_time,
'available_seats': available_seats
}
def view_available_flights(self):
print("Available Flights:")
for flight_id, details in self.flights.items():
print(f"Flight ID: {flight_id}, Departure City: {details['departure_city']}, Arrival City: {details['arrival_city']}, Depar
ble Seats: {details['available_seats']}")
def search_for_flights(self, criterion, value):
found_flights = []
for flight_id, details in self.flights.items():
if details[criterion] == value:
found_flights.append((flight_id, details))
return found_flights
def book_flight(self, flight_id, num_seats):
if flight_id in self.flights:
if self.flights[flight_id]['available_seats'] >= num_seats:
self.flights[flight_id]['available_seats'] -= num_seats
print(f"Successfully booked {num_seats} seats for flight {flight_id}")
else:
print("Not enough seats available for booking.")
else:
print("Invalid flight ID.")
def cancel_reservation(self, flight_id, num_seats):
if flight_id in self.flights:
self.flights[flight_id]['available_seats'] += num_seats
print(f"{num_seats} seats canceled for flight {flight_id}")
else:
print("Invalid flight ID.")
def view_booked_flights(self):
print("Booked Flights:")
for flight_id, details in self.flights.items():
booked_seats = details['available_seats']
available_seats = details['available_seats']
print(f"Flight ID: {flight_id}, Departure City: {details['departure_city']}, Arrival City: {details['arrival_city']}, Depar
Seats: {booked_seats}, Available Seats: {available_seats}")
# Example usage:
flight_system = FlightBookingSystem()
flight_system.add_flight(1, 'New York', 'London', '08:00', 200)
flight_system.add_flight(2, 'London', 'Paris', '10:00', 150)
flight_system.add_flight(3, 'Paris', 'Rome', '12:00', 180)
# View available flights
flight_system.view_available_flights()
# Search for flights
found_flights = flight_system.search_for_flights('departure_city', 'London')
print("Flights departing from London:")
for flight_id, details in found_flights:
print(f"Flight ID: {flight_id}, Departure City: {details['departure_city']}, Arrival City: {details['arrival_city']}, Departure
s: {details['available_seats']}")
# Book a flight
flight_system.book_flight(2, 2)
# Cancel reservation
flight_system.cancel_reservation(2, 1)
# View booked flights
flight_system.view_booked_flights()
9.
import math
num = 25
sqrt_num = math.sqrt(num)
print("Square root of", num, "is", sqrt_num)
import math
angle = math.pi / 6 # 30 degrees in radians
sin_value = math.sin(angle)
cos_value = math.cos(angle)
tan_value = math.tan(angle)
print("Sine of", angle, "is", sin_value)
print("Cosine of", angle, "is", cos_value)
print("Tangent of", angle, "is", tan_value)
import math
num = 4.7
ceil_value = math.ceil(num)
floor_value = math.floor(num)
print("Ceiling of", num, "is", ceil_value)
print("Floor of", num, "is", floor_value)
import random
random_num = random.randint(1, 100)
print("Random integer between 1 and 100:", random_num)
import random
colors = ['red', 'blue', 'green', 'yellow']
random_color = random.choice(colors)
print("Randomly chosen color:", random_color)
import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print("Shuffled list:", numbers)
10.
import math
def distance_2d(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def distance_3d(x1, y1, z1, x2, y2, z2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
# Example usage:
print("Distance between two points in 2D space:", distance_2d(1, 2, 4, 6))
print("Distance between two points in 3D space:", distance_3d(1, 2, 3, 4, 5, 6))
import math
import matplotlib.pyplot as plt
def euler_method(f, x0, y0, h, n):
"""
Solves the ODE y' = f(x, y) using Euler's method.
f: Function representing the ODE, taking x and y as arguments.
x0, y0: Initial conditions.
h: Step size.
n: Number of steps.
"""
x_values = [x0]
y_values = [y0]
for i in range(n):
x = x_values[-1]
y = y_values[-1]
slope = f(x, y)
x_new = x + h
y_new = y + h * slope
x_values.append(x_new)
y_values.append(y_new)
return x_values, y_values
# Define the ODE representing a damped harmonic oscillator
def damped_harmonic_oscillator(x, y):
return -0.1 * y - math.sin(x)
# Initial conditions
x0 = 0
y0 = 1
# Step size and number of steps
h = 0.1
n = 100
# Solve the ODE using Euler's method
x_values, y_values = euler_method(damped_harmonic_oscillator, x0, y0, h, n)
# Plot the solution
plt.plot(x_values, y_values)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Solution of Damped Harmonic Oscillator using Euler\'s Method')
plt.grid(True)
plt.show()
11.
import random
def roll_dice():
return random.randint(1, 6)
def simulate_rolling(num_trials):
results = {i: 0 for i in range(2, 13)} # Initialize dictionary to store results
for _ in range(num_trials):
die1 = roll_dice()
die2 = roll_dice()
total = die1 + die2
results[total] += 1
return results
def print_results(results):
print("Sum of Dice\tOccurrences")
print("-------------------------")
for total, count in results.items():
print(f"{total}\t\t{count}")
# Simulate rolling the dice 100 times
results = simulate_rolling(100)
# Print the results in tabular format
print_results(results)
import random
import string
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length))
# Example usage: Generate a random password of length 10
password = generate_password(10)
print("Randomly generated password:", password)
12.
import datetime
def find_nth_day(n):
# Get the current date
current_date = datetime.datetime.now().date()
print("Current date is", current_date.strftime("%d/%m/%Y"))
# Calculate Nth day before and after the current date
before_date = current_date - datetime.timedelta(days=n)
after_date = current_date + datetime.timedelta(days=n)
# Get the day names for before and after dates
before_day_name = before_date.strftime("%A")
after_day_name = after_date.strftime("%A")
# Print the results
print(f"{n} days before: {before_date.strftime('%d/%m/%Y')} - {before_day_name}")
print(f"After {n} days: {after_date.strftime('%d/%m/%Y')} - {after_day_name}")
# Sample input
N=5
find_nth_day(N)
13.
import datetime
def days_between_dates(date1, date2):
# Convert date strings to datetime objects
date1 = datetime.datetime.strptime(date1, "%Y-%m-%d").date()
date2 = datetime.datetime.strptime(date2, "%Y-%m-%d").date()
# Calculate the difference between the dates
delta = abs(date2 - date1)
# Return the number of days
return delta.days
# Example usage:
date_str1 = "2024-03-26"
date_str2 = "2024-04-05"
print("Number of days between", date_str1, "and", date_str2, "is:", days_between_dates(date_str1, date_str2))