DAY 03 ยท PRACTICE

Python + Java Questions ๐Ÿ’ช

๐Ÿ“ฆ Topics: List ยท Tuple ยท Set ยท Dict ยท OOP ยท File Handling โฑ Est: 3โ€“4 hrs total ๐ŸŽฏ Difficulty: 2/5

๐Ÿ Python โ€” Day 3

5 questions ยท List, Tuple, Set, Dict, OOP, File Handling ยท Difficulty 2/5

01
Daily Expense Tracker ๐Ÿ’ฐ
PYTHON LIST FILE EASY ~30 min
๐Ÿ“– Scenario
You want to track your daily expenses. Each expense is stored as a dictionary with "item" and "amount". You need to save them to a file and load them back โ€” just like a real expense app saves your data!
๐Ÿ’ก New concept: File Handling
open("file.txt", "w") โ†’ write mode (creates file)
open("file.txt", "a") โ†’ append mode (adds to existing)
open("file.txt", "r") โ†’ read mode
Always use with open(...) as f: โ€” it auto-closes the file!
Starter Data
expenses = [ {"item": "Lunch", "amount": 120}, {"item": "Bus", "amount": 30}, {"item": "Coffee", "amount": 60}, {"item": "Dinner", "amount": 200}, {"item": "Snacks", "amount": 45}, ] # Write your functions below
Your Tasks
  • Write a save_expenses(expenses, filename) function that saves each expense as a line: Lunch,120 Use "w" mode. Write item and amount separated by comma.
  • Write a load_expenses(filename) function that reads the file back and returns a list of dicts Split each line by comma, convert amount to int
  • Write a summary(expenses) function that returns: total spent, most expensive item, cheapest item Use max() and min() with key=lambda
  • Save expenses to expenses.txt, load it back, and print the summary
Expected Output
Saved to expenses.txt!
Loaded 5 expenses.
Total spent: โ‚น455
Most expensive: Dinner (โ‚น200)
Cheapest: Bus (โ‚น30)
๐Ÿ’ก One Hint
To write: f.write(f"{e['item']},{e['amount']}\n") for each expense.
To read back: line.strip().split(",") gives you ["Lunch", "120"]
02
Movie Rating System ๐ŸŽฌ
PYTHON TUPLE DICT EASY ~25 min
๐Ÿ“– Scenario
You are building a movie rating system like IMDb. Each movie is stored as a tuple โ€” (title, genre, rating). Tuples are used because movie data shouldn't change once recorded. You need to filter, group, and analyze them.
Starter Data
movies = [ ("Inception", "Sci-Fi", 8.8), ("The Godfather", "Drama", 9.2), ("Interstellar", "Sci-Fi", 8.6), ("Coco", "Animation",8.4), ("Parasite", "Drama", 8.6), ("Toy Story", "Animation",8.3), ] # movie[0]=title, movie[1]=genre, movie[2]=rating
Your Tasks
  • Find all movies with rating above 8.5 โ€” return their titles only
  • Group movies by genre โ€” return a dict: {"Sci-Fi": [...], "Drama": [...]} Each value is a list of movie titles in that genre
  • Find the highest rated movie in each genre Return dict: {"Sci-Fi": ("Inception", 8.8), ...}
  • Calculate the average rating of all movies
Expected Output
Above 8.5: ['Inception', 'The Godfather', 'Interstellar', 'Parasite']
Genre groups: {'Sci-Fi': ['Inception','Interstellar'], 'Drama': ['The Godfather','Parasite'], 'Animation': ['Coco','Toy Story']}
Best per genre: {'Sci-Fi': ('Inception',8.8), 'Drama': ('The Godfather',9.2), 'Animation': ('Coco',8.4)}
Average rating: 8.65
๐Ÿ’ก One Hint
For grouping by genre, use dict.setdefault(genre, []).append(title) โ€” this creates the key if it doesn't exist and appends to the list!
03
Course Enrollment Checker ๐ŸŽ“
PYTHON SET DICT EASY ~20 min
๐Ÿ“– Scenario
A university has students enrolled in different courses. Using sets, you can instantly find which students are in multiple courses, who is only in one course, and how many unique students there are โ€” no loops needed!
Starter Data
python_class = {"Rahul", "Priya", "Arjun", "Sneha", "Karan"} java_class = {"Priya", "Arjun", "Vikram", "Neha"} ml_class = {"Sneha", "Vikram", "Rahul", "Divya"}
Your Tasks
  • Find students enrolled in both Python AND Java
  • Find students in Python only (not in Java or ML)
  • Find all unique students across all 3 courses
  • Find students enrolled in all 3 courses at once
  • Count how many students are in exactly one course Hint: use symmetric difference or manual checking
Expected Output
Python โˆฉ Java: {'Priya', 'Arjun'}
Python only: {'Karan', 'Rahul'} (not in Java or ML... wait Rahul is in ML! โ†’ {'Karan'})
All students: {'Rahul','Priya','Arjun','Sneha','Karan','Vikram','Neha','Divya'}
In all 3: set() (nobody!)
In exactly 1 course: {'Karan', 'Neha', 'Divya'} โ†’ 3 students
๐Ÿ’ก One Hint
"Python only" means in python_class but NOT in java_class and NOT in ml_class:
python_class - java_class - ml_class
04
Library Book System ๐Ÿ“š
PYTHON OOP LIST EASY ~35 min
๐Ÿ“– Scenario
Build a simple library system. A Book class stores book info. A Library class manages a collection of books โ€” you can add books, search by author, and check out (borrow) a book. If a book is already borrowed, show an error!
๐Ÿ’ก New OOP concept: Composition
One class can contain objects of another class!
Library has a list of Book objects โ€” that's composition.
It's like a school that contains students โ€” school IS NOT a student, but it HAS students!
Starter Template
class Book: def __init__(self, title, author, pages): pass # store title, author, pages, is_borrowed=False def __str__(self): pass # return "Title by Author (pages pg)" class Library: def __init__(self): self.books = [] def add_book(self, book): pass def search_by_author(self, author): pass def checkout(self, title): pass def return_book(self, title): pass
Your Tasks
  • Complete Book.__init__ โ€” store title, author, pages. Add is_borrowed = False
  • Complete Book.__str__ โ€” returns a readable string like "Atomic Habits by James Clear (320 pg)"
  • Complete Library.add_book โ€” append book to self.books list
  • Complete Library.search_by_author โ€” return list of all books by that author
  • Complete checkout โ€” if not borrowed โ†’ mark as borrowed. If already borrowed โ†’ print "Already checked out!" Also complete return_book โ€” reverse of checkout
Expected Output
lib.add_book(Book("Atomic Habits", "James Clear", 320))
lib.checkout("Atomic Habits") โ†’ "Checked out: Atomic Habits"
lib.checkout("Atomic Habits") โ†’ "Already checked out!"
lib.return_book("Atomic Habits") โ†’ "Returned: Atomic Habits"
lib.search_by_author("James Clear") โ†’ [Atomic Habits by James Clear (320 pg)]
๐Ÿ’ก One Hint
In checkout, loop through self.books to find the book by title. Use book.is_borrowed to check status and set it to True when borrowed.
05
Word Frequency Counter ๐Ÿ“
PYTHON DICT FILE LIST EASY ~25 min
๐Ÿ“– Scenario
You are building a tool that reads a paragraph from a file and counts how many times each word appears โ€” like Google's word analysis tool. This combines file reading with dictionary counting!
Starter Code
# First create sample.txt with this content: text = """python is great python is easy java is also great programming is fun python and java are both popular""" with open("sample.txt", "w") as f: f.write(text) # Now write these functions:
Your Tasks
  • Write count_words(filename) โ€” reads file, returns dict of word frequencies Lowercase all words. Split by spaces. Count each word.
  • Write top_n_words(freq_dict, n) โ€” returns top N most frequent words as list of tuples Sort by count descending, return first n items
  • Write words_appearing_once(freq_dict) โ€” returns list of words that appear exactly once
  • Save the frequency results back to word_report.txt โ€” one word per line: python: 3
Expected Output
count_words โ†’ {'python':3, 'is':4, 'great':2, 'easy':1, 'java':2, 'also':1, 'programming':1, 'fun':1, 'and':1, 'are':1, 'both':1, 'popular':1}
top_3 โ†’ [('is',4), ('python',3), ('great',2)]
appearing once โ†’ ['easy','also','programming','fun','and','are','both','popular']
๐Ÿ’ก One Hint
For counting: freq[word] = freq.get(word, 0) + 1 โ€” this adds 1 to existing count or starts at 0 if word is new. No need to check if key exists!

โ˜• Java โ€” Day 3

5 questions ยท ArrayList, HashMap, HashSet, OOP, File I/O ยท Difficulty 2/5

01
Student Grade Manager ๐Ÿ“
JAVA ARRAYLIST HASHMAP EASY ~30 min
๐Ÿ“– Scenario
You are building a grade management system. Student names and marks are stored in a HashMap. You need to find the topper, calculate average, and get pass/fail lists โ€” just like a school portal!
๐Ÿ’ก Java equivalent of Python dict โ†’ HashMap
Python: {"Rahul": 72}
Java: HashMap<String, Integer> grades = new HashMap<>();
Add: grades.put("Rahul", 72);
Get: grades.get("Rahul");
Loop: for (Map.Entry<String,Integer> e : grades.entrySet())
Starter Code
import java.util.*; public class GradeManager { public static void main(String[] args) { HashMap<String, Integer> grades = new HashMap<>(); grades.put("Rahul", 72); grades.put("Priya", 85); grades.put("Arjun", 40); grades.put("Sneha", 91); grades.put("Vikram", 55); // Write your code here } }
Your Tasks
  • Calculate and print the average marks of the class
  • Print names of all students who passed (marks >= 50)
  • Print names of all students who failed (marks < 50)
  • Find and print the topper's name (highest marks) Loop through entrySet() and track the max manually
Expected Output
Average: 68.6
Passed: [Rahul, Priya, Sneha, Vikram]
Failed: [Arjun]
Topper: Sneha with 91 marks
๐Ÿ’ก One Hint
To loop through a HashMap: for (Map.Entry<String,Integer> entry : grades.entrySet()) { entry.getKey(); entry.getValue(); }
02
Common Friends Finder ๐Ÿ‘ซ
JAVA HASHSET EASY ~20 min
๐Ÿ“– Scenario
Same Instagram mutual friends concept โ€” but in Java! HashSet is Java's equivalent of Python's set. It automatically removes duplicates and supports set operations like intersection and union.
๐Ÿ’ก Java Set operations
Python A & B โ†’ Java: setA.retainAll(setB) (modifies setA!)
Python A - B โ†’ Java: setA.removeAll(setB) (modifies setA!)
Python A | B โ†’ Java: setA.addAll(setB) (modifies setA!)
Important: Always work on a COPY โ†’ new HashSet<>(setA)
Starter Code
import java.util.*; public class FriendFinder { public static void main(String[] args) { HashSet<String> rahulFriends = new HashSet<>( Arrays.asList("Amit","Priya","Rohan","Sneha","Karan") ); HashSet<String> priyaFriends = new HashSet<>( Arrays.asList("Rohan","Sneha","Ankit","Divya") ); // Write your code here โ€” use copies! } }
Your Tasks
  • Find common friends (intersection) Make a copy of rahulFriends first, then use retainAll(priyaFriends)
  • Find friends that are only Rahul's (difference)
  • Find all friends combined (union, no duplicates)
  • Print total count of unique friends
Expected Output
Common: [Rohan, Sneha]
Only Rahul's: [Amit, Priya, Karan]
All friends: [Amit, Priya, Rohan, Sneha, Karan, Ankit, Divya]
Total unique: 7
๐Ÿ’ก One Hint
Always copy before modifying: HashSet<String> common = new HashSet<>(rahulFriends); then common.retainAll(priyaFriends);. If you don't copy, you'll destroy the original set!
03
Simple Bank Account ๐Ÿฆ
JAVA OOP INHERITANCE EASY ~35 min
๐Ÿ“– Scenario
Build a bank account system in Java. A BankAccount class handles deposits and withdrawals. A SavingsAccount subclass adds interest logic. This is exactly like Python's class/inheritance โ€” just different syntax!
๐Ÿ’ก Python vs Java OOP comparison
Python: class SavingsAccount(BankAccount):
Java: class SavingsAccount extends BankAccount

Python: super().__init__(name, balance)
Java: super(name, balance);

Python: raise Exception("msg")
Java: throw new Exception("msg");
Starter Template
public class BankAccount { protected String name; protected double balance; public BankAccount(String name, double balance) { // store name and balance } public void deposit(double amt) { /* add to balance */ } public void withdraw(double amt) { /* subtract if enough */ } public void display() { /* print name + balance */ } } class SavingsAccount extends BankAccount { public SavingsAccount(String name, double balance) { super(name, balance); // call parent constructor } public void addInterest() { /* add 5% interest */ } }
Your Tasks
  • Complete BankAccount constructor โ€” store name and balance using this.name = name
  • Complete deposit โ€” add amt to balance and print "Deposited: X | Balance: Y"
  • Complete withdraw โ€” if amt > balance print "Insufficient funds!", else subtract and print balance
  • Complete display โ€” print account holder name and current balance
  • Complete SavingsAccount.addInterest โ€” multiply balance by 1.05 and print new balance
Expected Output
acc.deposit(500) โ†’ Deposited: 500.0 | Balance: 1500.0
acc.withdraw(200) โ†’ Withdrawn: 200.0 | Balance: 1300.0
acc.withdraw(5000) โ†’ Insufficient funds!
sav.addInterest() โ†’ Interest added! New balance: 2100.0
๐Ÿ’ก One Hint
In Java, use this.balance += amt to add to the balance. The keyword this refers to the current object โ€” same as Python's self!
04
Cricket Score Tracker ๐Ÿ
JAVA ARRAYLIST COLLECTIONS EASY ~25 min
๐Ÿ“– Scenario
Build a cricket scorecard in Java. Player scores are stored in an ArrayList of custom Player objects. You need to find the highest scorer, filter 50+ scorers, and calculate the team total โ€” same logic as Python but Java syntax!
๐Ÿ’ก Python List vs Java ArrayList
Python: scores = [] โ†’ scores.append(x)
Java: ArrayList<Player> scores = new ArrayList<>(); โ†’ scores.add(x);

Python: for p in scores:
Java: for (Player p : scores)
Starter Code
import java.util.*; class Player { String name; int runs; public Player(String name, int runs) { this.name = name; this.runs = runs; } } public class CricketTracker { public static void main(String[] args) { ArrayList<Player> team = new ArrayList<>(); team.add(new Player("Rohit", 83)); team.add(new Player("Virat", 45)); team.add(new Player("Dhoni", 67)); team.add(new Player("Hardik", 32)); team.add(new Player("Shubman", 91)); // Write your code here } }
Your Tasks
  • Calculate and print the total runs of the team
  • Find and print the highest scorer (name + runs)
  • Print all players who scored 50 or more runs
  • Calculate and print the team average
Expected Output
Total runs: 318
Highest scorer: Shubman - 91 runs
50+ scorers: Rohit(83), Dhoni(67), Shubman(91)
Team average: 63.6
๐Ÿ’ก One Hint
To loop and find max manually: start with Player highest = team.get(0); then loop โ€” if p.runs > highest.runs, update highest = p;
05
Student Record File Writer ๐Ÿ“
JAVA FILE I/O OOP EASY ~30 min
๐Ÿ“– Scenario
Write a program that saves student records to a file and reads them back. In Java, file handling uses FileWriter and BufferedReader โ€” more verbose than Python but same idea. Write once, read many times!
๐Ÿ’ก Python vs Java File Handling
Python write: with open("f.txt","w") as f: f.write(text)
Java write: FileWriter fw = new FileWriter("f.txt"); fw.write(text); fw.close();

Python read: with open("f.txt","r") as f: lines = f.readlines()
Java read: BufferedReader br = new BufferedReader(new FileReader("f.txt"));
Then: String line = br.readLine(); in a loop until null
Starter Template
import java.io.*; import java.util.*; public class StudentFileManager { static String[][] students = { {"Rahul", "72"}, {"Priya", "85"}, {"Arjun", "40"}, {"Sneha", "91"} }; public static void saveToFile(String filename) throws IOException { // Write each student as "Name,Marks" on each line } public static void readFromFile(String filename) throws IOException { // Read each line, split by comma, print name and marks } public static void main(String[] args) throws IOException { saveToFile("students.txt"); readFromFile("students.txt"); } }
Your Tasks
  • Complete saveToFile โ€” write each student as Rahul,72 on a new line using FileWriter
  • Complete readFromFile โ€” read each line using BufferedReader, split by comma, print name and marks
  • In main, after reading, also print: total students count, and the name of the student with highest marks You'll need to parse marks to int using Integer.parseInt()
Expected Output
Saved 4 students to students.txt
--- Reading from file ---
Rahul: 72 marks
Priya: 85 marks
Arjun: 40 marks
Sneha: 91 marks
Total students: 4 | Topper: Sneha (91)
๐Ÿ’ก One Hint
For FileWriter: FileWriter fw = new FileWriter(filename); fw.write(name + "," + marks + "\n"); fw.close();
For BufferedReader: String line; while ((line = br.readLine()) != null) { String[] parts = line.split(","); }