# 1. Pythagorean Triplets

import math
start = 1
end = 100

for i in range(start,end):
    for j in range(i,end):
        k = math.isqrt(i*i+j*j)
        if k <= end and k*k == (i*i+j*j):
            print(i,j,k)

# 2. Add 1 to Each Digit

n = '12390'
print(''.join(str((int(i)+1)%10) for i in n))

# 3. Decimal, Octal, Binary, Hexadecimal

for i in range(1,10):
    print(f"{i:d} {i:b} {i:o} {i:x}")

# 4. Sum of First 10 Prime Numbers

p = [n for n in range(2,30) if all(n%i for i in range(2,n))]
print(sum(p[:10]))

# 5. Average of N Numbers

n = 3
s = 0
for i in range(n):
    s+=float(input("N :"))
print("Avg : ",s/n if n else 0)

# 6. Armstrong Numbers in a Range

a, b = map(int, input("Range: ").split())
for n in range(max(0,a), b+1):
    if n == sum(int(i)**len(str(n)) for i in str(n)):
        print(n)

# 7. Strong Numbers in a Range

from math import factorial
a, b = map(int, input("Range: ").split())
for n in range(max(0,a), b+1):
    if n == sum(factorial(int(i)) for i in str(n)):
        print(n)


# 8. Hollow Square Pattern

for i in range(5):
    print("*****" if i in (0,4) else "*   *")

# 9. Numbers Not Divisible by 2 or 3

n = int(input("N: "))
a = [i for i in range(1,n+1) if i%2 and i%3]
print(a)
print("Count:", len(a))

# 10. Square Pattern with @

for i in range(5):
    print("**@**" if i == 2 else "*****")

# 11. Pascal's Triangle

# import math

n = 5
for i in range(n):
    print(" "*(n-i), *(math.comb(i,j) for j in range(i+1)))

# 12. Sum of Series (1 + 1/2! + ... + 1/n!)

from math import factorial
n = 5
print(sum(1/factorial(i) for i in range(1,n+1)))

# 13. Multiplication Tables of Odd Numbers

a, b = map(int, input("Range: ").split())
for n in range(a,b+1):
    if n%2:
        for i in range(1,11):
            print(n, "x", i, "=", n*i)

# 14. Triangle

rows = 5
for i in range(1, rows + 1):
    spaces = " " * (rows - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)


# Q2 – NumPy Case Studies

# 1. Climate Data Analysis

import numpy as np

np.random.seed(1)

cities = ["Mumbai", "Pune", "Delhi", "Chennai", "Kolkata"]
temps = np.random.randint(25, 42, size=(5, 7))
print(temps)

avg = temps.mean(axis=1)
for i in range(5):
    print(f"Average temp of {cities[i]}: {avg[i]:.2f}")

row, col = np.unravel_index(temps.argmax(), temps.shape)
print(f"Hottest day overall: Day {col + 1} in {cities[row]} ({temps[row, col]} C)")

for i in range(5):
    print(f"Hottest day in {cities[i]}: Day {temps[i].argmax() + 1}")

print("City with highest average:", cities[avg.argmax()])

hot_days = np.where((temps > 35).any(axis=0))[0] + 1
print("Days when any city went above 35 C:", hot_days)

# OR

import numpy as np
a = np.random.randint(20, 41, (5, 7))
print("Data:\n", a)
print("City averages:", a.mean(axis=1))
print("Hottest overall:", np.unravel_index(a.argmax(), a.shape))
print("Hottest day per city:", a.argmax(axis=1)+1)
print("Hottest city:", a.mean(axis=1).argmax()+1)
print("Days above 35:", np.where((a>35).any(axis=0))[0]+1)



# 2. RGB to Grayscale and Binary Image

image = np.random.randint(0, 256, size=(4, 4, 3))
gray = 0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] + 0.114 * image[:, :, 2]
print("Grayscale:\n", gray.round(1))
binary = np.where(gray > 128, 255, 0)
print("Binary:\n", binary)

# OR

import numpy as np
rgb = np.array([[[255,0,0],[0,255,0]],
                [[0,0,255],[255,255,255]]])
gray = np.dot(rgb, [0.299,0.587,0.114])
binary = np.where(gray>128, 255, 0)
print("Gray:\n", gray)
print("Binary:\n", binary)


# 3. Genomic Data Processing

dna = np.random.choice(["A", "T", "C", "G"], size=30)
print("DNA:", "".join(dna))

bases, counts = np.unique(dna, return_counts=True)
for b, c in zip(bases, counts):
    print(f"{b} : {c}")
print("Most common base:", bases[counts.argmax()])

threshold = 2   # find runs of the same base longer than this
print(f"Repeated sequences longer than {threshold}:")
run = 1
for i in range(1, len(dna) + 1):
    if i < len(dna) and dna[i] == dna[i - 1]:
        run += 1
    else:
        if run > threshold:
            print(dna[i - 1] * run)
        run = 1

print("Reversed DNA:", "".join(dna[::-1]))

# OR

import numpy as np
from itertools import groupby
dna = np.array(list("AATCCCGGGGTA"))
bases, counts = np.unique(dna, return_counts=True)
print(dict(zip(bases, counts)))
print("Most common:", bases[counts.argmax()])
# n = int(input("Threshold: "))
n = 2
print("Runs:", [''.join(g) for _, group in groupby(dna) if len(g:=list(group))>n])
print("Reverse:", ''.join(dna[::-1]))


# 4. Stock Price Analysis

stocks = ["Stock A", "Stock B", "Stock C", "Stock D"]
prices = np.random.uniform(80, 120, size=(10, 4)).round(2)   # 10 days x 4 stocks
print(prices)

change = (prices[1:] - prices[:-1]) / prices[:-1] * 100
print("Daily % change:\n", change.round(2))

variance = change.var(axis=0)
print("Most volatile stock:", stocks[variance.argmax()])

total_return = (prices[-1] - prices[0]) / prices[0] * 100
print("Best performing stock:", stocks[total_return.argmax()],
      f"({total_return.max():.2f}%)")

days, stock_idx = np.where(change < -5)
for d, s in zip(days, stock_idx):
    print(f"{stocks[s]} dropped {abs(change[d, s]):.2f}% on Day {d + 2}")

# OR

import numpy as np
p = np.random.randint(100, 200, (10, 4)).astype(float)
r = np.diff(p, axis=0)/p[:-1]*100
print("Prices:\n", p)
print("Daily returns:\n", r)
print("Most volatile stock:", r.var(axis=0).argmax()+1)
print("Best stock:", (p[-1]/p[0]).argmax()+1)
print("Days with >5% drop:", np.where((r<-5).any(axis=1))[0]+2)


# 1. Retail Sales Data Analysis

sales = [
    {"product_name":"Pen","category":"Stationery","units_sold":20,"unit_price":10},
    {"product_name":"Book","category":"Stationery","units_sold":5,"unit_price":100},
    {"product_name":"Milk","category":"Food","units_sold":10,"unit_price":50}
]
total = sum(x["units_sold"]*x["unit_price"] for x in sales)
print("Total:", total, "Average:", total/len(sales))
print("Top product:", max(sales,key=lambda x:x["units_sold"])["product_name"])
for c in set(x["category"] for x in sales):
    print(c, sum(x["units_sold"]*x["unit_price"] for x in sales if x["category"]==c))

# 2. Student Grades Management System

students = [
    {"student_name":"Ankur","grades":{"Math":85,"Science":92,"English":78}},
    {"student_name":"Riya","grades":{"Math":90,"Science":95,"English":88}}
]
avg = lambda s: sum(s["grades"].values())/len(s["grades"])
for s in students:
    print(s["student_name"], "Average:", avg(s))
print("Top:", max(students,key=avg)["student_name"])
print("Lowest:", min(students,key=avg)["student_name"])
print("Class average:", sum(map(avg,students))/len(students))
print("Distribution:", {
    g:sum(1 for s in students if (avg(s)>=90 if g=="A" else
    75<=avg(s)<90 if g=="B" else avg(s)<75))
    for g in ("A","B","C")
})

# 3. Library Management System

from datetime import date
books = [
    {"title":"Python","author":"Guido","checked_out":True,"due_date":"2024-08-01","borrow_count":5},
    {"title":"Java","author":"James","checked_out":False,"due_date":None,"borrow_count":2}
]
print("Available:", sum(not b["checked_out"] for b in books))
print("Most borrowed:", max(books,key=lambda b:b["borrow_count"])["title"])
print("Overdue:", [b["title"] for b in books if b["checked_out"] and
                    date.fromisoformat(b["due_date"])<date.today()])
books[1]["checked_out"] = True
books[1]["due_date"] = "2027-01-01"
books[1]["borrow_count"] += 1
print("After checkout:", books)

# 4. Employee Attendance Tracker

from datetime import datetime
staff = [
    {"employee_name":"Rajesh","attendance":{"2024-08-15":("09:00","17:00"),"2024-08-16":("09:15","17:10")}},
    {"employee_name":"Ankur","attendance":{"2024-08-15":("09:00","18:00")}}
]
days = 2
for e in staff:
    hours = sum((datetime.strptime(b,"%H:%M")-datetime.strptime(a,"%H:%M")).total_seconds()/3600
                for a,b in e["attendance"].values())
    e["hours"], e["absences"] = hours, days-len(e["attendance"])
    print(e["employee_name"], "Hours:", round(hours,2), "Absences:", e["absences"])
print("Most hours:", max(staff,key=lambda e:e["hours"])["employee_name"])
print("Least hours:", min(staff,key=lambda e:e["hours"])["employee_name"])
print("Perfect:", [e["employee_name"] for e in staff if e["absences"]==0])
print("Most absent:", max(staff,key=lambda e:e["absences"])["employee_name"])

# Q3 – School Management System Using Inheritance

class Person:
    def __init__(self, name, age, pid):
        self.name, self.age, self.pid = name, age, pid

    def display(self):
        print(self.name, self.age, self.pid)

class Student(Person):
    def __init__(self, name, age, pid, grade):
        super().__init__(name, age, pid)
        self.grade, self.courses = grade, []

    def enroll(self, course):
        course.add_student(self)

    def display(self):
        super().display()
        print(self.grade, [c.name for c in self.courses])

class Teacher(Person):
    def __init__(self, name, age, pid, subject):
        super().__init__(name, age, pid)
        self.subject, self.courses = subject, []

    def assign(self, course):
        course.set_teacher(self)

    def display(self):
        super().display()
        print(self.subject, [c.name for c in self.courses])

class Course:
    def __init__(self, name, cid):
        self.name, self.cid = name, cid
        self.students, self.teacher = [], None

    def add_student(self, s):
        if s not in self.students:
            self.students.append(s)
            s.courses.append(self)

    def set_teacher(self, t):
        if self.teacher:
            self.teacher.courses.remove(self)
        self.teacher = t
        if self not in t.courses:
            t.courses.append(self)

    def display(self):
        print(self.name, self.cid)
        print("Teacher:", self.teacher.name if self.teacher else "None")
        print("Students:", [s.name for s in self.students])

    def average(self):
        return sum(s.grade for s in self.students)/len(self.students) if self.students else 0

class School:
    def __init__(self):
        self.students, self.teachers, self.courses = [], [], []

    def register_student(self, s):
        self.students.append(s)

    def register_teacher(self, t):
        self.teachers.append(t)

    def add_course(self, c):
        self.courses.append(c)

school = School()
s1 = Student("Ankur", 20, 1, 85)
s2 = Student("Riya", 19, 2, 90)
t = Teacher("Raj", 35, 101, "Python")
c = Course("Python", 201)

school.register_student(s1)
school.register_student(s2)
school.register_teacher(t)
school.add_course(c)

s1.enroll(c)
s2.enroll(c)
t.assign(c)

s1.display()
t.display()
c.display()
print("Average grade:", c.average())
print("Student courses:", [x.name for x in s1.courses])
print("Enrolled students:")
for s in c.students:
    s.display()


# Q4 – Vehicle Rental System Using Inheritance and Polymorphism

class Vehicle:
    def __init__(self, vid, brand, model, price):
        self.vid, self.brand, self.model = vid, brand, model
        self.price, self.__available = price, True

    @property
    def available(self):
        return self.__available

    def set_available(self, value):
        self.__available = value

    def cost(self, days):
        return self.price * days

    def display(self):
        print(self.vid, self.brand, self.model, self.price)

class Car(Vehicle):
    def __init__(self, vid, brand, model, price, seats):
        super().__init__(vid, brand, model, price)
        self.seats = seats

    def display(self):
        super().display()
        print("Seats:", self.seats)

class Bike(Vehicle):
    def __init__(self, vid, brand, model, price, engine):
        super().__init__(vid, brand, model, price)
        self.engine = engine

    def display(self):
        super().display()
        print("Engine:", self.engine)

class Truck(Vehicle):
    def __init__(self, vid, brand, model, price, load):
        super().__init__(vid, brand, model, price)
        self.load = load

    def display(self):
        super().display()
        print("Load:", self.load)

class Customer:
    def __init__(self, name, license_no):
        self.name, self.license_no = name, license_no
        self.rented, self.history = [], []

    def display(self):
        print(self.name, self.license_no)
        print("Rented:", [v.vid for v in self.rented])

    def show_history(self):
        for record in self.history:
            print(*record)

class RentalService:
    def __init__(self):
        self.vehicles, self.customers = {}, {}

    def add_vehicle(self, v):
        self.vehicles[v.vid] = v

    def register(self, c):
        self.customers[c.license_no] = c

    def show_available(self):
        for v in self.vehicles.values():
            if v.available:
                v.display()

    def rent(self, vid, license_no):
        v = self.vehicles.get(vid)
        c = self.customers.get(license_no)
        if not v or not c or not v.available:
            print("Rental unavailable")
            return
        v.set_available(False)
        c.rented.append(v)
        print("Rented:", v.model)

    def return_vehicle(self, vid, license_no, days):
        v = self.vehicles.get(vid)
        c = self.customers.get(license_no)
        if not c or not v or v not in c.rented or days <= 0:
            print("Invalid return")
            return
        cost = v.cost(days)
        v.set_available(True)
        c.rented.remove(v)
        c.history.append((v.model, days, cost))
        print("Total cost:", cost)

service = RentalService()

service.add_vehicle(Car(1, "Tata", "Nexon", 1500, 5))
service.add_vehicle(Bike(2, "Honda", "Shine", 500, 125))
service.add_vehicle(Truck(3, "Tata", "Ace", 2000, 1000))

customer = Customer("Ankur", "MH123")
service.register(customer)

print("Available vehicles:")
service.show_available()

service.rent(1, "MH123")
service.rent(1, "MH123")  # Already rented
customer.display()

service.return_vehicle(1, "MH123", 3)

print("Rental history:")
customer.show_history()

print("Available after return:")
service.show_available()
