Combined_Library_Management_and_Exercises
Combined_Library_Management_and_Exercises
Question 2
# Question 10: Max and Min from a set
nums = {4, 7, 1, 9, 3}
print("Maximum:", max(nums))
print("Minimum:", min(nums))
Question 3
# Question 11: Check for duplicates in a list
my_list = [1, 2, 3, 4, 2, 5]
if len(my_list) != len(set(my_list)):
print("List has duplicates")
else:
print("List has no duplicates")
Question 4
# Question 12: Class to store employee data
class Employee:
def __init__(self, name, year, salary, address):
self.name = name
self.year = year
self.salary = salary
self.address = address
def display(self):
print(f"{self.name}, {self.year}, {self.salary}, {self.address}")
e1.display()
e2.display()
e3.display()
Question 5
# Question 13: Rectangle class with area and perimeter
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
words = text.split()
freq = {}
def calculate_area():
r = float(entry.get())
area = pi * r * r
result.config(text=f"Area: {area:.2f}")
win = tk.Tk()
tk.Label(win, text="Enter radius:").pack()
entry = tk.Entry(win)
entry.pack()
tk.Button(win, text="Calculate", command=calculate_area).pack()
result = tk.Label(win)
result.pack()
win.mainloop()
Question 8
# Question 16: GUI to input personal info and display it styled
import tkinter as tk
def show_info():
info = f"{name.get()}, {street.get()}, {city.get()}, {pincode.get()}"
output.config(text=info, font=("Arial", 32, "italic"))
win = tk.Tk()
win.title("MyInfo")
tk.Label(win, text="Name").pack()
name = tk.Entry(win)
name.pack()
tk.Label(win, text="Street").pack()
street = tk.Entry(win)
street.pack()
tk.Label(win, text="City").pack()
city = tk.Entry(win)
city.pack()
tk.Label(win, text="Pincode").pack()
pincode = tk.Entry(win)
pincode.pack()
win.mainloop()
Question 9
# Question 17: Simple Library Management System
library = []
def issue_book(book):
if book not in library:
library.append(book)
print(f"{book} issued.")
else:
print(f"{book} already issued.")
def return_book(book):
if book in library:
library.remove(book)
print(f"{book} returned.")
else:
print(f"{book} was not issued.")
def view_books():
print("Issued books:", library)
issue_book("Python Basics")
issue_book("ML Guide")
view_books()
return_book("Python Basics")
view_books()
Question 10
# Question 18: String operations
s1 = input("Enter string 1: ")
s2 = input("Enter string 2: ")
nums = [1, 2, 2, 3, 4, 4, 5]
print("Unique elements:", get_unique(nums))
Question 13
# Question 21: Filter even and odd using lambda
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Shape:", arr.shape)
print("Size:", arr.size)
Question 15
# Question 23: Check if string starts with given char using lambda
check = lambda s, c: s.startswith(c)
if check(string, char):
print("Yes, string starts with", char)
else:
print("No, it doesn't start with", char)
Question 16
# Question 24: Dictionary from string with letter frequency
s = 'vcetresource'
freq = {}
for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
Question 17
# Question 25: Find max and min in a set
nums = {11, 4, 22, 7, 3}
print("Maximum:", max(nums))
print("Minimum:", min(nums))
Question 18
# Question 26: Check if sets have no elements in common
set1 = {1, 2, 3}
set2 = {4, 5, 6}
if set1.isdisjoint(set2):
print("No elements in common")
else:
print("Sets have common elements")
Question 19
# Question 27: Remove duplicates from a list
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(set(lst))
print("List without duplicates:", unique_lst)
Question 20
# Question 28: Separate even and odd numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even = []
odd = []
if op == '+':
print("Result:", a + b)
elif op == '-':
print("Result:", a - b)
elif op == '*':
print("Result:", a * b)
elif op == '/':
print("Result:", a / b)
else:
print("Invalid operator")
except ValueError:
print("Invalid input! Please enter numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Question 23
# Question 30: Calculate electricity bill
def calc_bill(units):
if units <= 100:
return 0
elif units <= 200:
return (units - 100) * 5
else:
return (100 * 5) + (units - 200) * 10
for i in range(5):
u = int(input(f"Enter units for user {i+1}: "))
print(f"Total bill: Rs.{calc_bill(u)}")
Question 24
# Question 31: Various operations on a string
string = '''Ants are found everywhere in the world. They make their home in
buildings, gardens etc. They live in anthills. Ants are very hardworking insects.
Throughout the summers they collect food for the winter season. Whenever
they find a sweet lying on the floor they stick to the sweet and carry it to their
home. Thus, in this way, they clean the floor. Ants are generally red and black
in colour. They have two eyes and six legs. They are social insects. They live
in groups or colonies. Most ants are scavengers they collect whatever food
they can find. They are usually wingless but they develop wings when they
reproduce. Their bites are quite painful.'''
words = string.split()
# c. Words containing i
contains_i = [w for w in words if 'i' in w]
print("Words containing 'i':", contains_i)
# Main program:
import mymodule
mymodule.greet("Student")
Question 26
# Question 33: Matrix addition using nested lists
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
result = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
result[i][j] = a[i][j] + b[i][j]
print("Sum of matrices:")
for row in result:
print(row)
Question 27
# Question 34: Different types of plots
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 6, 7]
plt.subplot(1, 3, 1)
plt.plot(x, y)
plt.title("Line Plot")
plt.subplot(1, 3, 2)
plt.bar(x, y)
plt.title("Bar Plot")
plt.subplot(1, 3, 3)
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.tight_layout()
plt.show()
Question 28
# Question 35: Basic data manipulation with pandas
import pandas as pd
data = {
"Name": ["A", "B", "C"],
"Marks": [85, 90, 95]
}
df = pd.DataFrame(data)
print("Original Data:\n", df)
# Ascending
asc = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print("Ascending:", asc)
# Descending
desc = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True))
print("Descending:", desc)
Question 30
# Question 37: Get top 3 most expensive items
shop = {'item1': 45.50, 'item2': 35, 'item3': 41.30, 'item4': 55, 'item5': 24}
top_items = sorted(shop.items(), key=lambda x: x[1], reverse=True)[:3]
def add_book(book):
library[book] = "Available"
def issue_book(book):
if book in library and library[book] == "Available":
library[book] = "Issued"
print(f"{book} has been issued.")
else:
print(f"{book} is not available.")
def return_book(book):
if book in library and library[book] == "Issued":
library[book] = "Available"
print(f"{book} has been returned.")
def view_books():
print("Library Books:")
for book, status in library.items():
print(f"{book} - {status}")
# Sample usage
add_book("Python 101")
add_book("AI Basics")
view_books()
issue_book("Python 101")
view_books()
return_book("Python 101")
view_books()
Question 32
# Question 4: Calculate area and perimeter of a rectangle
def area(length, breadth):
return length * breadth
def display():
name = entry.get()
output.config(text="Record: " + name)
win = tk.Tk()
win.title("Simple GUI")
win.mainloop()
Question 34
# Question 6: Store marks and calculate total and percentage
marks = []
for i in range(5):
mark = float(input(f"Enter marks for subject {i+1}: "))
marks.append(mark)
total = sum(marks)
percentage = total / 5
def getArea(self):
return self.length * self.breadth
a = Area()
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
a.setDim(l, b)
print("Area of Rectangle:", a.getArea())
Question 36
# Question 8: Map two lists to dictionary
colors = ["red", "blue"]
hex_codes = ["#ff0000", "#00ff00"]
if elem in my_tuple:
print("Element exists in tuple")
else:
print("Element does not exist")
Question 38
cost_price = float(input("Enter the cost price of the bike: "))