0% found this document useful (0 votes)
5 views13 pages

Python Assignment

Uploaded by

huma shadmeen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views13 pages

Python Assignment

Uploaded by

huma shadmeen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

ASSIGNMENT 1

1. Write a program to read two integers and perform arithmetic


operations on them (addition, subtraction, multiplication and
division).

x = eval(input("Enter first integer :"))


y = eval(input("Enter second integer :"))
print("Addition =", x+y)
print("Subtraction =", x-y)
print("Multiplication =", x*y)
print("Division =", x/y)

2. You need to empty out the rectangular swimming pool which is 12


meters long, 7 meters wide and 2 meter depth. You have a pump
which can move 17 cubic meters of water in an hour. Write a
program to find how long it will take to empty your volume/time).

length = eval(input("Enter the length of the rectangular swimming pool :"))


breadth = eval(input("Enter the breadth of the rectangular swimming pool :"))
depth = eval(input("Enter the depth/height of the rectangular swimming pool
:"))
volume = length*breadth*depth
pump_rate = eval(input("Enter the pump rate :"))
time = volume/pump_rate
print("The time taken by the pump to empty the swimming pool is :" , time)
ASSIGNMENT 2
1. A car starts from a stoplight and is traveling with a velocity of 10
m/sec east in 20 seconds. Write a program to find the acceleration
of the car. [acc = (V(final)-V(initial)/Time].

initialv = 0
finalv = 10
time = 20
acceleration = (finalv - initialv)/time
print("Acceleration of the car is : " , acceleration , "m/s^2")

2. Suppose you want to develop a program to play a lottery. The


program randomly generates a two-digit number, prompts the
user to enter a two wins according to the following rules:
-> If the user’s input matches the lottery in the exact order, the
award is $10,000.
-> If all the digits in the user’s input match all the digits in the
lottery number, the award is $3,000.
-> If one digit in the user’s input matches a digit in the lottery
number, the award is $1,000.

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

1. Program to Find the GCD of Two Positive Numbers.

x = eval(input("Enter first positive integer :"))


y = eval(input("Enter second positive integer :"))
if x>y:
while y!=0:
temp = y
y = x%y
x = temp
gcd = x
else:
while x!=0:
temp=x;
x = y%x
y = temp
gcd = y

print("The GCD is" , gcd)

2. Write a Program to Display the Fibonacci Sequences up to nth Term


Where n is Provided by the user.
n = eval(input( " Enter the value of n : "))
num1 = 0
num2 = 1
next_number = num2
count = 1
while count <= n:
print(next_number, end=" ")
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()
ASSIGNMENT 4
1. Write a program to find whether a number is prime or not. Make sure that
the asymptotic complexity of the program is < O(n).

n=eval(input("Enter a number : "))


if n==2:
print(n," is a prime no.")
else:
if n%2==0:
print(n,"It is not a prime no")
else :
if n==3:
print(n," is a prime no.")
else :
if n%3==0:
print(n,"It is not a prime no")
else:
print(n," is a prime no. ")

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.

def find_area(shape, *args, **kwargs):

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

# Calculate the area of a circle


a=eval(input("Enter the radius of circle"))
circle_area = find_area("circle", a)
print("Circle area:", circle_area)

# Calculate the area of a rectangle


l=eval(input("Enter the length of rectangle"))
b=eval(input("Enter the breadth of rectangle"))

rectangle_area = find_area("rectangle", l,b)


print("Rectangle area:", rectangle_area)

# Calculate the area of a right-angled triangle


b1=eval(input("Enter the base of triangle"))
h=eval(input("Enter the height of triangle"))
triangle_area = find_area("triangle", b1, h)
print("Triangle area:", triangle_area)
ASSIGNMENT 5
1. Write a program to check whether a given String is palindrome or not.

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

def add(self, numbers):


return sum(numbers)

def subtract(self, numbers):


result = numbers[0]
for num in numbers[1:]:
result -= num
return result

def power(self, base, exponent):


return base ** exponent

def root(self, number, n):

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

# Nth power of a number


elif choice == 3:
base = float(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
print("%.2f raised to the power of %d is: %.2f" % (base, exponent,
calc.power(base, exponent)))

# Nth root of a number


elif choice == 4:
number = float(input("Enter the number: "))
n = int(input("Enter the root value (n)(n shouldn't be 0): "))
result = calc.root(number, n)
print("The %dth root of %.2f is: %.2f" % (n, number, result))
else:
print("Invalid choice!")
2. Write a program to create an online grocery store class. Identify the data
members and member functions associated with this class. Identify the
category of items (fruits, vegetables, spices, toiletries, confectionary, baked
items, cereals, pulses, etc). It should be possible to add items into the cart and
make payment for the selected number and types of items.

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 add_item(self, cat_index, item_name, item_price):


# Add an item to the inventory
if 0 <= cat_index < len(self.categories):
self.items_by_cat[cat_index].append([item_name, item_price]) # Use a
list to store item details
else:
print("Category not found!")

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 add_to_cart(self, cat_index, item_name):


# Add an item to the shopping cart
if 0 <= cat_index < len(self.categories):
for item in self.items_by_cat[cat_index]:
if item[0] == item_name:
self.cart.append(item) # Add the item (list) to the cart
print(item_name + " has been added to your cart.")
return
print(item_name + " not found in the " + self.categories[cat_index] + "
category.")
else:
print("Category not found!")

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

# Adding items to the inventory (using category index)


store.add_item(0, 'Apple', 0.50) # Fruits
store.add_item(0, 'Banana', 0.30) # Fruits
store.add_item(1, 'Carrot', 0.40) # Vegetables
store.add_item(2, 'Salt', 1.00) # Spices
store.add_item(3, 'Chocolate Bar', 1.50) # Confectionery
store.add_item(4, 'Bread', 2.00) # Baked Goods

# Viewing available items


store.show_inventory()

# Ask user to add items to the cart


while True:
category_choice = int(input("Enter the category index to add item to cart (0
to " + str(len(store.categories) - 1) + "), or -1 to finish: "))
if category_choice == -1:
break
item_name = input("Enter the item name to add to your cart: ")
store.add_to_cart(category_choice, item_name)

# Viewing cart
store.show_cart()

# Making payment
store.make_payment()

# Viewing cart after payment


store.show_cart()
ASSIGNMENT 7

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

elements = input(f"Enter the elements of set {i+1} (space-separated):


").split()

sets.append(set(map(int, elements)))

result = sets[0]

for s in sets[1:]:
result = result.intersection(s)

return result

intersection = find_intersection()

print("The intersection of all sets is:", intersection)

You might also like