Skip to main content

Set B - Question 3

3. a) Write a Python program to find the factorial of a number using recursion.

Write a Python program to input n numbers into a list and perform the following operations: i. Find the sum and average of the elements. ii. Find the maximum and minimum elements. iii. Display the list in ascending and descending order.

Answer

Part 1: Factorial using Recursion

def factorial(n):
"""
Calculates factorial of a non-negative integer recursively.
"""
# Base cases
if n == 0 or n == 1:
return 1
# Recursive case
return n * factorial(n - 1)

# Testing the recursive function
number = 5
print(f"Factorial of {number} is: {factorial(number)}") # Outputs 120

Part 2: Program for List Operations on N Input Numbers

# Simulating input of n numbers into a list
# In a real environment, you can prompt the user:
# n = int(input("Enter number of elements: "))
# numbers = [float(input(f"Enter element {i+1}: ")) for i in range(n)]

simulated_input = [15, 42, 8, 91, 23, 76]
numbers = list(simulated_input)
print("Input List:", numbers)

# i. Find the sum and average of the elements
total_sum = sum(numbers)
average = total_sum / len(numbers) if len(numbers) > 0 else 0
print(f"i. Sum: {total_sum}")
print(f" Average: {average:.2f}")

# ii. Find the maximum and minimum elements
min_val = min(numbers)
max_val = max(numbers)
print(f"ii. Minimum Element: {min_val}")
print(f" Maximum Element: {max_val}")

# iii. Display the list in ascending and descending order
ascending = sorted(numbers)
descending = sorted(numbers, reverse=True)
print(f"iii. Ascending Order: {ascending}")
print(f" Descending Order: {descending}")

3. b) A dataset students.csv has columns StudentID, Gender, Marks_Math, Marks_Science, Marks_English. Perform EDA to:

Perform the following EDA tasks:

  • Find average marks per subject.
  • Identify top-performing students.
  • Plot subject-wise score distribution using histograms. (Include direct, concise, exam-ready Python script solving these tasks with a quick dataset setup).

Answer

Here is the complete, concise, exam-ready Python program implementing the entire EDA pipeline, including automated mock dataset generation for execution:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os

# 1. Quick dataset setup
csv_file = "students.csv"
if not os.path.exists(csv_file):
# Generates a quick mock CSV for execution safety
np.random.seed(42)
mock_df = pd.DataFrame({
"StudentID": [f"STU{i:03d}" for i in range(1, 51)],
"Gender": np.random.choice(["Male", "Female"], size=50),
"Marks_Math": np.random.randint(40, 100, size=50),
"Marks_Science": np.random.randint(45, 100, size=50),
"Marks_English": np.random.randint(35, 100, size=50)
})
mock_df.to_csv(csv_file, index=False)

# Load the dataset
df_students = pd.read_csv(csv_file)
subjects = ["Marks_Math", "Marks_Science", "Marks_English"]


# Task 1: Find average marks per subject
print("=== 1. Average Marks Per Subject ===")
avg_marks = df_students[subjects].mean()
for subject, avg_val in avg_marks.items():
sub_name = subject.split("_")[1]
print(f"Average in {sub_name:<7}: {avg_val:.2f}%")
print()


# Task 2: Identify top-performing students
print("=== 2. Top-Performing Students ===")
# Define total marks by summing all subjects row-wise
df_students["Total_Marks"] = df_students[subjects].sum(axis=1)
# Rank and filter to get top 5 students
top_students = df_students.sort_values(by="Total_Marks", ascending=False).head(5)
print(top_students[["StudentID", "Gender", "Total_Marks"]])
print()


# Task 3: Plot subject-wise score distribution using histograms
print("=== 3. Plotting Distributions ===")
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5), sharey=True)
colors = ['#1f77b4', '#2ca02c', '#9467bd']
titles = ["Math Score Distribution", "Science Score Distribution", "English Score Distribution"]

for i, sub in enumerate(subjects):
ax = axes[i]
ax.hist(df_students[sub], bins=10, range=(30, 100), color=colors[i], edgecolor='black', alpha=0.7)

# Highlight median
median_val = df_students[sub].median()
ax.axvline(median_val, color='red', linestyle='--', linewidth=1.5, label=f'Median: {median_val}')

ax.set_title(titles[i], fontsize=11, fontweight='bold')
ax.set_xlabel('Marks %', fontsize=9)
ax.grid(True, linestyle=':', alpha=0.5)
ax.legend(loc='upper left')

axes[0].set_ylabel('Number of Students', fontsize=9)
plt.suptitle('Subject-Wise Score Distributions', fontsize=13, fontweight='bold', y=1.02)
plt.tight_layout()
plt.show()