# WEEK 0 ASSIGNMENT (DEADLINE : 8/12/2025 11:59 AM) --- **GENERAL INSTRUCTIONS:** **(TOTAL MARKS = 100 + 100 (BONUS))** 1. Hello everyone, the wait is over!!! We hope you made full use of the resources provided to you for Python Programming. Sorry for the delay, but here it is -- **your first assignment of FAP 2025/26 : SynchroMind** 2. Please go through all the **instructions** carefully (section-wiseand question-wise) about the marking scheme, how many questions to attempt, what you need to solve exactly and what you need to submit. 3. Solve all the questions in a `.ipynb` notebook with proper code-block division (use Markdown with proper question number and name) for each question. **Recommened Online Code Editors :** Kaggle, Google Colab (easy for beginners). 4. Download the `.ipynb` file and upload it on the Week 0 Assignment Folder of the **official GitHub repository** of the project (shared to you in the official whatsapp group -- with details instructions). **Only those submissions will be accepted.** (Guidelines and resources for GitHub have been provided in the group. Hope you have gone through it, but don't worry if you face any issue in setting up or understanding, Mentors are always there to help you out!!!) 5. Some questions are tricky, we admit. This is not to test you nor your average semester exams, but just to give you something mind-boggling and fun-to-solve problems. Don't worry, if you are stuck at any point of time, you can always reach out to any of the four Mentors at any given point of time to clarify your doubts. 6. **ALSO, REMEMBER:** We **ONLY** look for your genuine enthusiasm to learn and even your efforts to attempt the problems. We are not here to judge professional submissions. Take this assignment as a beginning of your journey in logic-building and programming which is going to help you in the long-run. 7. **SUBMISSION FILE NAMING :** `<First_Name>_<Roll_No>.ipynb` **(COMPULSORY TO FOLLOW)** Upload it under the right folder. 8. We know the submission deadline is a bit strict **(EXTENSION IS NOT POSSIBLE)**. But sorry, we could not help about that as we are already running a bit late in the project with Week 0. Try to attempt as much as you can **(Passing Marks = 0, but expect ALL of you to make submission)** and Don't stress yourself about the deadline right now. Happy coding guys :) --- --- **LEVEL 0 : (ATTEMPT ALL FIVE) (25 marks)** --- **Q1 : BASIC PYTHON (5 marks)** Write a Python function: ``` def filter_long_words(words, min_length): """ words: list of strings min_length: integer returns: new list of words whose length is >= min_length """ ``` Example: ``` words = ["cat", "elephant", "dog", "hippopotamus", "ant"] min_length = 4 # Expected output: ["elephant", "hippopotamus"] ``` --- **Q2. BASIC NUMPY (5 marks)** Using **NumPy**: 1. Create a 1D NumPy array containing the integers from 1 to 10. 2. Compute: * The sum of all elements * The mean (average) * A new array where each element is squared 3. Reshape the original array into a 2D array of shape `(2, 5)`. Write a script that prints: * The original array * The sum, mean * The squared array * The reshaped array --- **Q3. BASIC PANDAS (5 marks)** You have a CSV file `students.csv` with the following columns: * `name` (string) * `age` (integer) * `grade` (float, between 0 and 100) * `subject` (string) Using **pandas**: * Read the CSV into a DataFrame. * Print the first 5 rows. * Filter and display only the students with `grade >= 80`. Compute and print the average grade per subject. --- **Q4. BASIC MATPLOTLIB (5 marks)** Using **Matplotlib**: 1. Generate `x` values from 0 to 10 with a small step (e.g. 0.1) using NumPy. 2. Define `y = x**2` (square of x). 3. Plot `y` vs `x` as a line plot. 4. Add: * A title: `"Square Function"` * X-label: `"x"` * Y-label: `"x squared"` 5. Show the plot. --- **Q5. BASIC SEABORN (5 marks)** **Seaborn** is a Python data visualization library built on top of matplotlib, designed to make high-level statistical plots easier to create and much better looking with minimal code. Resources -- 1. https://www.geeksforgeeks.org/python/introduction-to-seaborn-python/ (geeksforgeeks tutorial) 2. https://youtu.be/6GUZXDef2U0?si=n9AZ2VtTeixIyGen (youtube tutorial -- 1 hour course) 3. https://youtu.be/ooqXQ37XHMM?si=XpwJ25ZxL0LMH0qZ (youtube tutorial -- NeuralNine compact video) Using **seaborn** (and optionally pandas): 1. Create a small DataFrame with columns: * `height` (in cm) * `weight` (in kg) * `gender` (values like `"Male"` / `"Female`") 3. Use seaborn to plot a scatter plot of `weight` vs `height`. 4. Color the points by `gender` (using the hue parameter). 5. Add a title like `"Height vs Weight by Gender"`. --- --- **LEVEL 1 :** **(ATTEMPT ALL THREE)** **(30 marks)** --- **Q6 : ROTATE ONCE-IN PLACE** **(10 marks)** You are given a list arr of length n (possibly n = 0 or n = 1). Write a function: ``` def rotate_right_by_one(arr): ... ``` that rotates the list to the right by 1 in-place: ``` Example: [1, 2, 3, 4] → [4, 1, 2, 3] Example: [] → [], [7] → [7] ``` You are not allowed to use pop() or insert() or slicing in one fancy line like arr[:] = arr[-1:] + arr[:-1]. Do it with **index manipulation** and **loops**. --- **Q7 : TRICKY FUNCTION OUTPUT** **(10 marks)** Consider: ``` def add_item(x, bucket=[]): bucket.append(x) return bucket ``` Predict the output of: ``` print(add_item(1)) print(add_item(2)) print(add_item(3, [])) print(add_item(4)) ``` Then, rewrite `add_item` so that it behaves as most people “intuitively expect”: * A fresh list every time if the user doesn’t pass `bucket` * Then, show the most expected answer [ which misleads you to the wrong answer for the above question :( ]. --- **Q8 : COUNT PEAKS** **(10 marks)** Given an integer list nums, a peak is an index i such that: 0 < i < len(nums)-1 nums[i] > nums[i-1] and nums[i] > nums[i+1] Write: ``` def count_peaks(nums): ... ``` Return the number of peaks. ``` Example: nums = [1, 3, 2, 4, 1] → peaks at indices 1 and 3 → answer = 2 ``` Think carefully about lists of length < 3 and boundary cases. --- --- **LEVEL 2 :** **(ATTEMPT ANY ONE)** **(20 marks)** --- **Q9 : LONGEST EQUAL SUBARRAY** **(20 marks)** Given a list of integers nums, find the length of the longest contiguous subarray where all elements are equal. ``` def longest_equal_segment(nums): ... ``` Example: ``` [1, 1, 2, 2, 2, 3] → longest equal segment is [2, 2, 2] → 3 [7, 7, 7] → 3 [] → 0 ``` This is easy logically, but it’s very easy to mess up the reset logic. --- **Q10. SHADOWING VARIABLES** **(20 marks)** You have the following code: ``` x = 10 def f(): print("Inside f, before:", x) x = 5 print("Inside f, after:", x) f() print("Outside:", x) ``` 1. What error do you get, and why? 2. Modify the function so that: * Version A: It changes the global `x` to 5. * Version B: It uses a local variable named `x` but does not cause an error and does not affect the global `x`. (Do this without renaming `x`.) --- **Q11. FREQUENCY OF NEAREGT GREATEST ELEMENT** **(20 marks)** You are given a list arr of distinct integers. For each element `arr[i]`, define: * NGE(i) = the nearest element to the right of i that is greater than `arr[i]`. * If none exists, ignore that index. Now count how many times each value appears as an `NGE` for some index. Write: ``` def nearest_greater_frequency(arr): """ Return a dict mapping value -> count_of_times_it_is_NGE. """ ``` Example: `arr = [2, 5, 3, 7, 1]` For each index: ``` 2 → nearest greater is 5 5 → nearest greater is 7 3 → nearest greater is 7 7 → no greater to the right 1 → none ``` So frequencies: ``` 5: 1, 7: 2 Return {5: 1, 7: 2}. ``` --- --- **LEVEL 3 : (ATTEMPT ANY ONE) (25 marks)** --- **Q12 : SLIDING WINDOW PROBLEM** **(25 marks)** You’re given: * A list of non-negative integers `nums` * An integer `K` Find the maximum length of a contiguous subarray such that the sum of its elements is ≤ K. ``` def longest_subarray_at_most_k(nums, K): ... ``` Example: * nums = `[2, 1, 3, 2, 4, 3`], K = 7 * Longest subarray with sum ≤ 7 is `[2, 1, 3, 1]` (if that existed) or `[1, 3, 2, 1]` etc * You’ll have to compute for actual values. Trick: Optimal solution is O(n) using a sliding window. --- **Q13 : GROUP ANAGRAMS (25 marks)** Given a list of strings `words`, group them into lists of anagrams: ``` def group_anagrams(words): ... ``` Example: ``` ["eat", "tea", "tan", "ate", "nat", "bat"] → [ ["eat", "tea", "ate"], ["tan", "nat"], ["bat"] ] ``` Use a dictionary where: * Key = "signature" of an anagram group (e.g., sorted tuple of characters) * Value = list of words with that signature. **Trick:** The order of groups and order inside each group **doesn’t matter**; but your key design and dict usage have to be clean. --- --- **BONUS QUESTION : PAINTING THE FENCE** **(100 marks)** You are given a fence made of N wooden planks in a row, numbered from `1` to `N`. Each plank i must be painted up to an exact height `H[i]` (in units). Initially, all planks have height 0. You have only one type of operation: **Operation:** Choose any contiguous segment of planks `[L, R]` (1 ≤ L ≤ R ≤ N) and increase the height of every plank from L to R by exactly 1 unit. You can use this operation any number of times (including zero), but you must ensure that in the end, for every plank i, its height is exactly `H[i]`. You are not allowed to overpaint any plank beyond its target height. Your task is to find the minimum number of operations needed to reach the target configuration. --- **Input** The input consists of multiple test cases. The first line contains an integer `T` — the number of test cases. **For each test case:** The first line contains an integer `N` — the number of planks. The second line contains N integers `H[1], H[2], ..., H[N]` — the target heights of the planks. **Constraints:** `1 ≤ T ≤ 10^5` `1 ≤ N ≤ 2 * 10^5 over all test cases (sum of N across test cases ≤ 2 * 10^5)` `0 ≤ H[i] ≤ 10^9` It is guaranteed that the input is such that it is always possible to reach the target configuration using the allowed operation. You should implement an efficient solution (around O(N) per test case) — a naive simulation will be too slow. **Output** For each test case, print a single integer — the minimum number of operations required to obtain the given target heights. --- **Example** **Input** ``` 2 3 2 2 1 5 1 3 2 1 2 ``` --- **Output** ``` 2 4 ``` --- **Explanation (just for better understanding)** Test case 1: `H = [2, 2, 1]` One optimal sequence of operations: Paint planks 1 to 3 → heights become `[1, 1, 1]` Paint planks 1 to 2 → heights become `[2, 2, 1]` You can’t do it in fewer than 2 operations. Test case 2: `H = [1, 3, 2, 1, 2]` One valid way (not necessarily unique) uses 4 operations. The problem is to figure out what the minimum is, and why. --- **Important Instructions:** 1. The code should be modular (easily understandable functions, non-AI generated variable and parameter names. The logic should be freely-flowing. Comment out codelines for better understanding) 2. You should submit a small report explaining your approach to the problem and the logic that you built to arrive at the solution. 3. To help you out, I am providing a sketch of psuedo-codefor you to start approaching this problem :) : ``` function solve(): read T for each test case in 1..T: read N read array H[1..N] prev = 0 ans = 0 for i = 1 to N: if H[i] > prev: ans = ans + (H[i] - prev) prev = H[i] print ans ``` 4. Your code will be evaluated on some hidden test cases (to be revealed to you after submission deadline with their score weightages). Your scores will be made available to you in the official Whatsapp group. So, your code should be executable when we run the script on our local systems for evaluation. 5. It is absolutely okay if you could not implement it in code, but I am expecting that you present a clean report on the problem approach and logic building. --- --- **Mentors (and their contacts):** 1. Archisman Dhar (6295490117) 2. Dhruv Gupta (9606174940) 3. Kritik Gupta (9215658030) 4. Keshav Agarwal (9493052512) --- ---