Untitled 2
Untitled 2
def is_geometric(li):
if len(li) <= 1:
return True
# Calculate ratio
ratio = li[1]/ oat(li[0])
# Check the ratio of the remaining
for i in range(1, len(li)):
if li[i]/ oat(li[i-1]) != ratio:
return False
return True
print(is_geometric([5, 8, 9, 11]))
fl
fl
Question 2: Write
a Python program to nd the
largest palindrome made from
the product of two 4-digit
numbers.
n=0
for a in range(9999, 100, -1):
for b in range(a, 100, -1):
x=a*b
if x > n:
s = str(a * b)
if s == s[::-1]:
n=a*b
print(n)
fi
Question 3: Write
a python program to nd the
smallest positive number that is
evenly divisible by all of the numbers
from 1 to 30.2520 is the smallest
number that can be divided by each
of the numbers from 1 to 10 without
any remainder.
n=1
for i in range(1, 31):
n = lcm(n, i)
print(n)
fi
Question 4: Write a Python program to nd the rst triangle
number to have over n(given) divisors.
def count_divisors(num):
count = 0
for i in range(1, int(num**0.5) + 1):
if num % i == 0:
count += 1
if i != num // i: # Count both divisors
count += 1
return count
def rst_triangle_with_over_n_divisors(n):
k=1
while True:
# Calculate the k-th triangular number
triangular_number = k * (k + 1) // 2
k += 1
if __name__ == "__main__":
n = int(input("Enter the number of divisors: "))
result = rst_triangle_with_over_n_divisors(n)
print(f"The rst triangular number with more than {n} divisors
is: {result}”)
fi
fi
fi
fi
fi
Question 5: write a python program that reads text from a le and
writes it into another le but in the reverse order.
def reverse_text_in_ le(input_ le, output_ le):
try:
except FileNotFoundError:
print(f"Error: The le '{input_ le}' was not found.")
except IOError as e:
print(f"Error occurred while reading/writing les: {e}")
# Example usage
if __name__ == "__main__":
# Specify the input and output le names
input_ lename = 'input.txt' # Change this to your input le
path
output_ lename = 'output.txt' # Change this to your desired
output le path
print(generate_square_roots(number1,
number2))
fl
fl
fl
fi
Question 7:Write a program that overloads /= operator fraction
class. Throw an exception if a divide by zero exception occurs.
class Fraction:
def __str__(self):
return f"{self.numerator}/{self.denominator}"
except ZeroDivisionError as e:
print(f"Error: {e}")
except ValueError as e:
print(f"Error: {e}")
except TypeError as e:
print(f"Error: {e}")
# Example usage
try:
fraction1 = Fraction(1, 2)
fraction2 = Fraction(2, 3)
print(f"Before division:
{fraction1}")
fraction1 /= fraction2
print(f"After division: {fraction1}")
def __init__(self):
self.no_of_seats_ rst = 0
self.no_of_seats_second = 0
self.no_of_seats_third = 0
self.no_of_chars = 0
def display_data(self):
print(f"Number of Seats (1st Class):
{self.no_of_seats_ rst}")
print(f"Number of Seats (2nd Class):
{self.no_of_seats_second}")
print(f"Number of Seats (3rd Class):
{self.no_of_seats_third}")
print(f"Number of Characters: {self.no_of_chars}")
fi
fi
fi
fi
fi
class Reservation(Distance):
def __init__(self):
super().__init__()
self.seats_booked_ rst = 0
self.seats_booked_second = 0
self.seats_booked_third = 0
def display_status(self):
print(f"Seats Booked (1st Class): {self.seats_booked_ rst}")
print(f"Seats Booked (2nd Class){self.seats_booked_second}")
print(f"Seats Booked (3rd Class): {self.seats_booked_third}")
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
# Example usage:
def main():
distance = Reservation()
# Booking tickets
distance.book_tickets( rst=5, second=10, third=20)
distance.display_status()
# Cancelling tickets
distance.cancel_tickets( rst=2, second=5, third=10)
distance.display_status()
if __name__ == "__main__":
main()
fi
fi
fi
fi
fi
fi
Question 9: write a python program that has class distance with
members kms and meters .derive classes school and of ce which
store the distance from your house to school and of ce along with
other details.
class Distance:
def __init__(self, kms=0, meters=0):
self.kms = kms
self.meters = meters
def display_distance(self):
""" Display the distance in a readable format. """
total_meters = self.kms * 1000 + self.meters
print(f"Distance: {self.kms} km and {self.meters} meters
(Total: {total_meters} meters)")
class School(Distance):
def __init__(self, school_name, kms=0, meters=0):
super().__init__(kms, meters)
self.school_name = school_name
def display_details(self):
""" Display the distance to the school along with its name. """
print(f"School Name: {self.school_name}")
self.display_distance()
fi
fi
class Of ce(Distance):
def __init__(self, of ce_name, kms=0, meters=0):
super().__init__(kms, meters)
self.of ce_name = of ce_name
def display_details(self):
""" Display the distance to the of ce along with its
name. """
print(f"Of ce Name: {self.of ce_name}")
self.display_distance()
# Example usage:
def main():
# Creating an instance for School
school = School(school_name="ABC High School",
kms=2, meters=500)
school.display_details()
if __name__ == "__main__":
main()
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Question 10: write a program using highest precedence to
lowest.
def operator_precedence_demo():
# Parentheses to override precedence
expression1 = (5 + 3) * 2 # Addition inside parentheses
takes precedence
expression2 = 10 - (2 ** 3) # Exponentiation takes
precedence over subtraction
expression3 = 4 * 3 + 2 # Multiplication takes
precedence over addition
expression4 = (8 + 2) * (3 - 1) # Both sets of parentheses
evaluated rst
expression5 = 10 >= 5 and 5 < 10 # Comparison and
logical operators
expression6 = (12 / 4) + (3 * 2) - (1 % 2) # Mixing
various operations
expression7 = 5 + 6 * 2 - 1 / 2 # Shows priority of
multiplication & division over addition & subtraction
# Displaying results
print(f"Expression 1 ((5 + 3) * 2): {expression1}")
print(f"Expression 2 (10 - (2 ** 3)): {expression2}")
print(f"Expression 3 (4 * 3 + 2): {expression3}")
print(f"Expression 4 ((8 + 2) * (3 - 1)): {expression4}")
print(f"Expression 5 (10 >= 5 and 5 < 10):
{expression5}")
print(f"Expression 6 ((12 / 4) + (3 * 2) - (1 % 2)):
{expression6}")
print(f"Expression 7 (5 + 6 * 2 - 1 / 2): {expression7}")
if __name__ == "__main__":
operator_precedence_demo()
fi
Question 11: write a program to nd the given number is prime or
not.
def is_prime(number):
"""Check if a number is prime."""
if number <= 1:
return False # 0 and 1 are not prime numbers
if number <= 3:
return True # 2 and 3 are prime numbers
return True
def main():
try:
# Input from user
num = int(input("Enter a number to check if it is prime: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
except ValueError:
print("Please enter a valid integer.")
fi
Question 11: write a program to nd the given number is prime or
not.
def is_prime(number):
"""Check if a number is prime."""
if number <= 1:
return False # 0 and 1 are not prime numbers
if number <= 3:
return True # 2 and 3 are prime numbers
return True
def main():
try:
# Input from user
num = int(input("Enter a number to check if it is prime: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
except ValueError:
print("Please enter a valid integer.")
fi
Question 13: Write a program to nd the greatest number
among three numbers.
def main():
try:
# Input from user
num1 = oat(input("Enter the rst number: "))
num2 = oat(input("Enter the second number: "))
num3 = oat(input("Enter the third number: "))
if __name__ == "__main__":
main()
fi
fl
fl
fl
fi
fi
fi
Question 14: Write a program to nd the grade of a student.
def determine_grade(marks):
f main():
try:
# Input from user
marks = oat(input("Enter your marks (0-100): "))
grade = determine_grade(marks)
print(f"Your grade is: {grade}")
except ValueError:
print("Please enter valid numeric marks.")
if __name__ == "__main__":
main()de
fl
fi
Question 15: Write a program
to print the table of 5 using for
loop.
def print_table_of_5():
"""Print the multiplication
table of 5."""
print("Multiplication Table
of 5:")
for i in range(1, 11): #
Loop from 1 to 10
result = 5 * i
print(f"5 x {i} =
{result}")
if __name__ == "__main__":
print_table_of_5()
Question 16: write a program to print star:-
(a)*
**
***
****
*****
def print_right_triangle(height):
for i in range(1, height + 1):
print("* " * i)
if __name__ == "__main__":
height = 5 # Change this value to change the height of
the triangle
print_right_triangle(height)
(b)*****
****
***
**
*
def print_stars_down(num):
# Loop to print stars downward
for i in range(num, 0, -1):
print("* " * i)
if __name__ == "__main__":
num_stars = 5 # Change this value to print more or
fewer stars
print_stars_down(num_stars)
Question 17: Write a program to print number:-
• A
22
333
4444
55555
def print_doubling_numbers(n):
for i in range(1, n + 1):
print(str(i) * i)
if __name__ == "__main__":
n = 5 # You can change this number
to print more or fewer lines
print_doubling_numbers(n)
• B
12
123
1234
12345
def print_right_triangle(height):
for i in range(1, height + 1):
for j in range(1, i + 1):
print(j, end=" ")
print() # For a new line
if __name__ == "__main__":
height = 5 # Change this value to
change the height of the triangle
print_right_triangle(height)
Question 18: Write a program using control
statements break and continue.
(a)Break
def print_numbers_with_break():
for i in range(1, 11):
if i == 5:
print("Breaking at 5")
break
print(i)
if __name__ == "__main__":
print_numbers_with_break()
(b)Continue
def print_numbers_with_continue():
for i in range(1, 11):
if i == 5:
print("Skipping 5")
continue
print(i)
if __name__ == "__main__":
print_numbers_with_continue()
Question 19: Write a program using in built string function.
def string_operations(user_string):
# Display the original string
print(f"Original String: {user_string}")
# 3. Convert to uppercase
upper_string = user_string.upper()
print(f"Uppercase: {upper_string}")
# 4. Convert to lowercase
lower_string = user_string.lower()
print(f"Lowercase: {lower_string}")
def bonacci_series(n):
series = []
for i in range(n):
series.append( bonacci(i))
return series
if __name__ == "__main__":
num_terms = int(input("Enter the number of terms in the
Fibonacci series: "))
if num_terms <= 0:
print("Please enter a positive integer.")
else:
result = bonacci_series(num_terms)
print(f"Fibonacci series with {num_terms} terms:
{result}")
fi
fi
fi
fi
fi
fi
fi
fi
Question 21: Write a program to check
whether a given number is an ugly number.
def is_ugly(num):
if num <= 0:
return False
if __name__ == "__main__":
# User input
number = int(input("Enter a number to
check if it's an ugly number: "))
if is_ugly(number):
print(f"{number} is an ugly number.")
else:
print(f"{number} is not an ugly
number.")
fi
Question 22: Write a program to nd whether it contains an
additive sequence or not.
def is_additive_sequence(nums):
n = len(nums)
if n < 3:
return False # At least 3 numbers are needed for an
additive sequence
if sequence == nums:
return True
return False
if __name__ == "__main__":
# User input
numbers = list(map(int, input("Enter a list of numbers
separated by spaces: ").strip().split()))
if is_additive_sequence(numbers):
print("The list contains an additive sequence.")
fi
fi
fi
fi