Python Assignment
Python Assignment
initialv = 0
finalv = 10
time = 20
acceleration = (finalv - initialv)/time
print("Acceleration of the car is : " , acceleration , "m/s^2")
import random
x = eval(input("Enter a two - digit number between 10-99 : "))
lottery = random.randint(10,99)
print(" The lottery number is : " , lottery)
lottery_digit1 = lottery//10
lottery_digit2 = lottery%10
x_digit1 = x//10
x_digit2 = x%10
if x == lottery:
print(" The award is $10,000 ")
elif x_digit1 == lottery_digit2 and x_digit2 == lottery_digit1:
print(" The award is $3,000 ")
elif x_digit1 == lottery_digit1 or x_digit1 == lottery_digit2 or x_digit2 ==
lottery_digit1 or x_digit2 == lottery_digit2:
print( " The award is $1,000 ")
else:
print( " You're out of luck! ")
ASSIGNMENT 3
2. Write a single function to find the area of circle, rectangle and a right-angled
triangle. Make use of the concept of keyword, positional and default
arguments.
if shape == "circle":
radius = args[0]
return 3.14159 * radius ** 2
elif shape == "rectangle":
length = args[0]
width = args[1]
return length * width
elif shape == "triangle":
base = args[0]
height = args[1]
return 0.5 * base * height
else:
raise ValueError("Invalid shape. Please specify circle, rectangle, or
triangle.")
def check_palindrome():
user_input = input("Enter a string: ")
if user_input == user_input[::-1]: # check if the string is equal to its reverse
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
check_palindrome()
2. Consider a set of n students having roll number 1 to n. A set of selected
students (a batch) need to be arranged in a line. However, there is an issue. A
batch will be incompatible if it contains two students with consecutive roll
numbers. Therefore, in a compatible batch, no two students have consecutive
roll numbers, is to be chosen. Any batch must have atleast 1 student. You
need to determine in how many ways a compatible batch can be chosen for
the given n. You need to write a recursive function to implement the idea.
Also, find the largest batch(es).
def find_batches(n, index=1, batch=None):
if batch is None:
batch = []
if index > n:
if len(batch) > 0:
print(batch)
return
# Recursive call excluding the current index
find_batches(n, index + 1, batch)
# Recursive call including the current index
if len(batch) == 0 or (index - batch[-1] > 1):
find_batches(n, index + 1, batch + [index])
def main():
n = int(input("Enter the number of students: "))
print("The sets are:")
find_batches(n)
main()
ASSIGNMENT 6
1. Write a program to implement calculator class. The functionalities present in
the class include addition and subtraction of 'n' numbers, nth power and nth
root of a number.
import math
class Calculator:
def __init__(self):
pass
return number ** (1 / n)
#Main Par
calc = Calculator()
print("Choose an operation:")
print("1. Addition of 'n' numbers")
print("2. Subtraction of 'n' numbers")
print("3. Nth power of a number")
print("4. Nth root of a number")
choice = int(input("Enter your choice (1-4): "))
#Addition of n numbers
if choice == 1:
n = int(input("How many numbers do you want to add? "))
numbers = []
for i in range(n):
num = float(input("Enter number %d: " % (i+1)))
numbers.append(num)
print("The sum is: %.2f" % calc.add(numbers))
# Subtraction of n numbers
elif choice == 2:
n = int(input("How many numbers do you want to subtract? "))
numbers = []
for i in range(n):
num = float(input("Enter number %d: " % (i+1)))
numbers.append(num)
print("The result of subtraction is: %.2f" % calc.subtract(numbers))
class GroceryStore:
def __init__(self):
# Initialize the grocery store with available items and cart
self.categories = ['fruits', 'vegetables', 'spices', 'toiletries', 'confectionery',
'baked goods', 'cereals', 'pulses']
self.items_by_cat = [[] for _ in self.categories] # List of lists for items in
each category
self.cart = [] # Shopping cart
def show_inventory(self):
# Display all items in the inventory by category with serial numbers
for i in range(len(self.categories)):
cat = self.categories[i]
print("\nCategory " + str(i) + ": " + cat.capitalize())
for item in self.items_by_cat[i]:
print(" - " + item[0] + " : $" + str(item[1]))
def show_cart(self):
# Display the items in the cart
if not self.cart:
print("Your cart is empty.")
return
total_price = 0
print("\nItems in your cart:")
for item in self.cart:
print(" - " + item[0] + " : $" + str(item[1]))
total_price += item[1]
print("Total: $" + str(total_price))
def make_payment(self):
# Simulate the payment process
if not self.cart:
print("Your cart is empty. Please add items before making a payment.")
return
total_price = sum(item[1] for item in self.cart) # Sum prices from cart
print("Processing payment for: $" + str(total_price))
self.cart.clear() # Clear the cart after payment
print("Payment successful. Thank you for shopping with us!")
# Main Program
store = GroceryStore()
# Viewing cart
store.show_cart()
# Making payment
store.make_payment()
1. Given a list of tuples representing coordinates, e.g., coords = [(1, 2), (2,
3), (3, 4), (1, 2)], write a function that counts the occurrences of each
unique coordinate. Return the result as a dictionary where each key is a
coordinate (a tuple), and the value is its count.
def count_coordinates():
coords = []
n = int(input("Enter the number of coordinates: "))
for _ in range(n):
x, y = map(int, input("Enter a coordinate (x y): ").split())
coords.append((x, y))
result = {}
for coord in coords:
if coord in result:
result[coord] += 1
else:
result[coord] = 1
return result
print(count_coordinates())
2. Given a list of sets (more than 3 sets), write a function that returns the
set of elements that appear in all sets (the intersection of all sets).
def find_intersection():
n = int(input("Enter the number of sets: "))
sets = []
for i in range(n):
sets.append(set(map(int, elements)))
result = sets[0]
for s in sets[1:]:
result = result.intersection(s)
return result
intersection = find_intersection()