0% found this document useful (0 votes)
3 views26 pages

Untitled 2

The document contains multiple Python programming tasks, each requiring the implementation of specific functionalities such as checking for geometric progression, finding the largest palindrome from products of 4-digit numbers, and calculating the smallest positive number divisible by a range of integers. It also includes tasks for handling file operations, creating classes for distance and reservations, and implementing operator overloading. Each task is accompanied by code snippets demonstrating the required logic and structure.

Uploaded by

HUNTER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

Untitled 2

The document contains multiple Python programming tasks, each requiring the implementation of specific functionalities such as checking for geometric progression, finding the largest palindrome from products of 4-digit numbers, and calculating the smallest positive number divisible by a range of integers. It also includes tasks for handling file operations, creating classes for distance and reservations, and implementing operator overloading. Each task is accompanied by code snippets demonstrating the required logic and structure.

Uploaded by

HUNTER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Question 1 : Write a Python program

to check a sequence of numbers is a


geometric progression or not.

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([2, 6, 18, 54]))

print(is_geometric([10, 5, 2.5, 1.25]))

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.

def gcd(x,y): return y and gcd(y, x %


y) or x
def lcm(x,y): return x * y / gcd(x,y)

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

# Count the divisors of the triangular number


divisors_count = count_divisors(triangular_number)

# Check if the number of divisors exceeds n


if divisors_count > n:
return triangular_number

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:

# Reading text from the input le


with open(input_ le, 'r') as in le:
content = in le.read()

# Reversing the content


reversed_content = content[::-1]

# Writing the reversed content to the output le


with open(output_ le, 'w') as out le:
out le.write(reversed_content)

print(f"Contents from '{input_ le}' have been reversed and


written to '{output_ le}'.")

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

reverse_text_in_ le(input_ lename, output_ lename)


fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Question 6: Write a program that nds
square root of a number .Throw a
exception if a negative number is
entered.
def generate_square_roots(number1,
number2):
try:
if number1 < 0:
raise ValueError
return number1 ** number2
except ValueError as ve:
print("Invalid input! Please enter
a positive integer or a oat value", ve)
number1 = oat(input("Enter the
number "))
number2 = oat(input("Enter square
root of "))

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 __init__(self, numerator, denominator):


if denominator == 0:
raise ValueError("Denominator cannot be zero.")
self.numerator = numerator
self.denominator = denominator

def __str__(self):
return f"{self.numerator}/{self.denominator}"

def __itruediv__(self, other):


if isinstance(other, Fraction):
# Perform division
if other.numerator == 0:
raise ZeroDivisionError("Cannot divide by zero
fraction.")
self.numerator *= other.denominator
self.denominator *= other.numerator
else:
raise TypeError("Unsupported type for division: " +
str(type(other)))
return self

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}")

# Trying to divide by zero


zero_fraction = Fraction(0, 1)
fraction1 /= zero_fraction # This
will raise an exception
except ZeroDivisionError as e:
print(f"Error: {e}")
except ValueError as e:
print(f"Error: {e}")
except TypeError as e:
print(f"Error: {e}")
Question 8: write a program that has a class Distance with
members no of seats 1st, no of seats 2, tier, and no_of_chars
and member functions to set and display data. derive a class
reservation that has data members seats booked 1st, seats
booked two tier and seats booked three tier and function
two book and cancel ticket and display status.
class Distance:

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 set_data(self, rst, second, third, chars):


self.no_of_seats_ rst = rst
self.no_of_seats_second = second
self.no_of_seats_third = third
self.no_of_chars = chars

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 book_tickets(self, rst, second, third):


if ( rst > self.no_of_seats_ rst - self.seats_booked_ rst) or \
(second > self.no_of_seats_second -
self.seats_booked_second) or \
(third > self.no_of_seats_third - self.seats_booked_third):
print("Not enough seats available for the requested
booking.")
return
self.seats_booked_ rst += rst
self.seats_booked_second += second
self.seats_booked_third += third
print("Booking successful!")

def cancel_tickets(self, rst, second, third):


if ( rst > self.seats_booked_ rst) or \
(second > self.seats_booked_second) or \
(third > self.seats_booked_third):
print("Error: Cannot cancel more tickets than booked.")
return

self.seats_booked_ rst -= rst


self.seats_booked_second -= second
self.seats_booked_third -= third
print("Cancellation successful!")

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()

# Setting the number of available seats


distance.set_data( rst=50, second=75, third=100,
chars=5)
distance.display_data()

# 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()

# Trying to book tickets with insuf cient seats


distance.book_tickets( rst=50, second=70, third=90)

# Trying to cancel more tickets than booked


distance.cancel_tickets( rst=5, second=10, third=30)

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 set_distance(self, kms, meters):


""" Set distance in kilometers and meters. """
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()

print() # Just for spacing

# Creating an instance for Of ce


of ce = Of ce(of ce_name="XYZ Corp", kms=5,
meters=300)
of ce.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

# Check for even number or divisible by 3


if number % 2 == 0 or number % 3 == 0:
return False

# Check for factors from 5 to the square root of the number


i=5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6

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

# Check for even number or divisible by 3


if number % 2 == 0 or number % 3 == 0:
return False

# Check for factors from 5 to the square root of the number


i=5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6

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 nd_greatest_number(num1, num2, num3):


"""Find the greatest number among three numbers."""
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3

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: "))

greatest = nd_greatest_number(num1, num2, num3)


print(f"The greatest number among {num1}, {num2},
and {num3} is: {greatest}")
except ValueError:
print("Please enter valid numbers.")

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):

"""Determine the grade based on the marks."""


if marks >= 90:
return 'A'
elif marks >= 80:
return 'B'
elif marks >= 70:
return 'C'
elif marks >= 60:
return 'D'
elif marks >= 50:
return 'E'
else:
return 'F'

f main():
try:
# Input from user
marks = oat(input("Enter your marks (0-100): "))

if marks < 0 or marks > 100:


print("Please enter marks in the range of 0 to 100.")
return

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}")

# 1. Length of the string


length = len(user_string)
print(f"Length of the string: {length}")

# 2. Count occurrences of a character (e.g., 'a')


count_a = user_string.count('a')
print(f"Count of 'a': {count_a}")

# 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}")

# 5. Check if the string starts with a speci c substring


starts_with_hello = user_string.startswith("Hello")
print(f"Starts with 'Hello': {starts_with_hello}”)

# 6. Check if the string ends with a speci c substring


ends_with_world = user_string.endswith("world!")
print(f"Ends with 'world!': {ends_with_world}")

# 7. Replace a substring (e.g., replace "world" with "Python")


replaced_string = user_string.replace("world", "Python")
print(f"Replaced 'world' with 'Python': {replaced_string}")
if __name__ == "__main__":
# User input
user_input = input("Enter a string: ")
string_operations(user_input)
fi
fi
Question 20: Write a program to nd bonacci series using
recursion.
def bonacci(n):
# Base case
if n <= 0:
return 0
elif n == 1:
return 1
else:
# Recursive case
return bonacci(n - 1) + bonacci(n - 2)

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

# Divide the number by 2, 3, and 5 as long


as we can
for prime in [2, 3, 5]:
while num % prime == 0:
num //= prime

# If the nal value is 1, it's an ugly number


return num == 1

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

# Try every combination of the rst two numbers


for i in range(1, n - 1):
for j in range(i + 1, n):
rst = nums[0:i]
second = nums[i:j]
sequence = rst + second

# Check if they can form an additive sequence


while len(sequence) < n:
next_num = sequence[-1] + sequence[-2]
sequence.append(next_num)

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

You might also like