Home

Learn Programming & Prepare for NPTEL Exams... Swayam Solver is your one-stop destination for NPTEL exam preparation.

NPTEL The Joy of Computing using Python July - 2025 | Swayam

 

NPTEL » The Joy of Computing using Python


  Please scroll down for latest Programs ðŸ‘‡ 



Week 2 - Programming Assignment 1

Due on 2025-08-07, 23:59 IST
Gautam Gambhir, freshly appointed head coach for India’s 2025 away Test series against England, has asked the new analyst, Aryan, to keep a quirky statistic:
“At the end of each day’s play,” Gambhir says, “tell me the total runs we scored in every odd-numbered over—1st, 3rd, 5th … all the way up to the last over bowled that day. It helps me spot momentum in the sessions where bowlers are freshest.”
Aryan realises the job boils down to simple maths: if n is the last over of the day (always a positive integer), he just needs the sum of all odd integers from 1 through n.
Your task is to step into Aryan’s shoes and automate this little ritual.
Input Format:
A single integer
Output Format:
A single integer: the sum of all odd numbers from 1 to n
Your last recorded submission was on 2025-08-02, 19:39 IST
Select the Language for this assignment. 
1
n = int(input())
2
total = 0
3
for i in range(1, n + 1, 2):
4
    total += i
5
print(total)
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
1
1
1\n
Passed after ignoring Presentation Error
Test Case 2
2
1
1\n
Passed after ignoring Presentation Error
Test Case 3
10
25
25\n
Passed after ignoring Presentation Error



Week 2 - Programming Assignment 2

Due on 2025-08-07, 23:59 IST
A high-security vault uses a custom PIN authentication mechanism. To reduce the chances of brute-force attacks, the system only allows PINs that are Neon Numbers.
The rule is:
A PIN is valid if the sum of the digits of its square equals the PIN itself.
Your Task: Write a Python program that reads a numeric PIN input by the user and validates whether it is a Neon Number or not.
Your last recorded submission was on 2025-08-02, 19:41 IST
Select the Language for this assignment. 
1
pin = int(input())
2
square = pin ** 2
3
digit_sum = sum(int(digit) for digit in str(square))
4
if digit_sum == pin:
5
    print("Neon Number")
6
else:
7
    print("Not Neon Number")
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
0
Neon Number
Neon Number\n
Passed after ignoring Presentation Error
Test Case 2
1
Neon Number
Neon Number\n
Passed after ignoring Presentation Error
Test Case 3
2
Not Neon Number
Not Neon Number\n
Passed after ignoring Presentation Error



Week 2 - Programming Assignment 3

Due on 2025-08-07, 23:59 IST
While analysing intercepted communications, TASC officer Srikant Tiwari suspects that some messages might be carrying hidden signals. One of the red flags used by the agency is the density of vowels in a message — unusually high vowel counts may indicate a coded alert.
To assist in screening these messages quickly, a script is needed to count the number of vowels in any given string.
Write a Python program that:
Takes a message as input.
Counts the number of vowels (a, e, i, o, u — both uppercase and lowercase).
Prints the vowel count.
Input Format:
A single line containing a string .
Output Format:
A single integer — the count of vowels (A, E, I, O, U in both uppercase and lowercase).
Your last recorded submission was on 2025-08-02, 19:43 IST
Select the Language for this assignment. 
1
message = input()
2
vowels = "aeiouAEIOU"
3
count = 0
4
for char in message:
5
    if char in vowels:
6
        count += 1
7
print(count)
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
hello
2
2\n
Passed after ignoring Presentation Error
Test Case 2
PYTHON
1
1\n
Passed after ignoring Presentation Error
Test Case 3
OpenAI 123
4
4\n
Passed after ignoring Presentation Error






Week 6 Programming Assignment : 1

Due on 2025-09-04, 23:59 IST

Problem: Robot Arithmetic Module – Engineering Constraint

At RoboCore Labs, engineers are developing an embedded system for a low-power educational robot.
Due to hardware limitations, the robot’s control unit cannot use the built-in multiplication operation.

As a member of the firmware team, your task is to implement a function that computes the product of two positive integers without using the * operator.

Requirements:

  1. Function Namemultiply

  2. Parameters:

    • a (positive integer)

    • b (positive integer)

  3. Constraints:

    • You may only use the + (addition) and - (subtraction) operators.

    • The * (multiplication) operator is strictly forbidden.

  4. Return Value:

    • The function should return the product of a and b.

  5. Implementation:

    • The solution must be implemented using recursion.

  6. Note:

    • Do not read input from the user.

    • Do not print output to the console.

Your last recorded submission was on 2025-08-31, 19:47 IST
Select the Language for this assignment. 
1
def multiply(a, b):
2
    if a == 0 or b == 0:
3
        return 0
4
    if a == 1:
5
        return b
6
    if b == 1:
7
        return a
8
    if a > b:
9
        return multiply(b, a)
10
    return a + multiply(a, b-1)
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
2
3
6
6\n
Passed after ignoring Presentation Error
Test Case 2
5
4
20
20\n
Passed after ignoring Presentation Error
Test Case 3
10
17
170
170\n
Passed after ignoring Presentation Error
Test Case 4
23
4
92
92\n
Passed after ignoring Presentation Error
Test Case 5
100
1
100
100\n
Passed after ignoring Presentation Error



Week 6 Programming Assignment : 2

Due on 2025-09-04, 23:59 IST

Problem: Searching Patient Records in a Health Analytics System

The hospital network MedNexus maintains a centralized database of patient record IDs.
These IDs are stored in sorted order to enable fast lookups.

You are part of the software development team tasked with optimizing the search functionality.
Since the system follows a recursive design pattern, you must implement a recursive version of the search algorithm to determine whether a given patient ID exists in the records.

Requirements

  1. Function Namesearch

  2. Parameters:

    • L → A sorted list of integers (patient record IDs).

    • k → An integer representing the ID to search for.

  3. Return Value:

    • Return True if k is present in L.

    • Return False if k is not present.

  4. Constraints:

    • Must use recursion.

    • No need to accept input from the user.

    • No need to print output to the console. Only the function definition is required.

Example

L = [101, 203, 307, 402, 509] k = 307 search(L, k) # Output: True
Your last recorded submission was on 2025-08-31, 19:49 IST
Select the Language for this assignment. 
1
def search(L, k):
2
    if not L:
3
        return False
4
    mid = len(L) // 2
5
    if L[mid] == k:
6
        return True
7
    elif k < L[mid]:
8
        return search(L[:mid], k)
9
    else:
10
        return search(L[mid+1:], k)
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
search([1, 2, 3, 4], 2)
True
True\n
Passed after ignoring Presentation Error
Test Case 2
search([10, 20, 30, 40, 50], 15)
False
False\n
Passed after ignoring Presentation Error
Test Case 3
search([-100, -10, 1, 10, 20, 30, 30, 40, 50], 31)
False
False\n
Passed after ignoring Presentation Error
Test Case 4
search([-100, -10, 1, 10, 20, 30, 30, 40, 50], 50)
True
True\n
Passed after ignoring Presentation Error
Test Case 5
search([-100, -10, 1, 10, 20, 30, 30, 40, 50], -100)
True
True\n
Passed after ignoring Presentation Error
Test Case 6
search([-100, -10, 1, 10, 20, 30, 30, 40, 50], -200)
False
False\n
Passed after ignoring Presentation Error
Test Case 7
search([10], 10)
True
True\n
Passed after ignoring Presentation Error



Week 6 : Programming Assignment 3

Due on 2025-09-04, 23:59 IST

Problem: Signal Propagation in Network Simulation

At NeuroLink Systems, researchers are developing a simulation to analyze how signals propagate in a neural network grid.

  • The network is represented as a square matrix A, where each entry represents the connection strength between neurons.

  • To study influence over multiple steps, the team must compute the matrix raised to a power m.

  • Each matrix multiplication represents one time step of propagation.

Your task is to implement a recursive function to compute the power of a matrix.


Requirements

  1. Function Namepower

  2. Parameters:

    • A: A square matrix (2D list of integers or floats).

    • m: A positive integer (exponent).

  3. Return Value:

    • The matrix A^m, computed recursively.

  4. Constraints:

    • Must use recursion.

    • No user input or console printing — only function definition required.


Example

A = [[1, 2], [3, 4]] m = 2 power(A, m) # Expected output: # [[7, 10], # [15, 22]] Hint: You may find it helpful to implement a helper function for matrix multiplication.
Your last recorded submission was on 2025-08-31, 19:52 IST
Select the Language for this assignment. 
1
def power(A, m):
2
    def multiply(M1, M2):
3
        n = len(M1)
4
        result = [[0] * n for _ in range(n)]
5
        for i in range(n):
6
            for j in range(n):
7
                for k in range(n):
8
                    result[i][j] += M1[i][k] * M2[k][j]
9
        return result
10
    if m == 1:
11
        return A
12
    if m % 2 == 0:
13
        half = power(A, m // 2)
14
        return multiply(half, half)
15
    else:
16
        return multiply(A, power(A, m - 1))
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
3
3
1,2,3
4,5,6
7,8,9
468,576,684\n
1062,1305,1548\n
1656,2034,2412
468,576,684\n
1062,1305,1548\n
1656,2034,2412\n
Passed after ignoring Presentation Error
Test Case 2
3
2
1,2,3
4,5,6
7,8,10
30,36,45\n
66,81,102\n
109,134,169
30,36,45\n
66,81,102\n
109,134,169\n
Passed after ignoring Presentation Error
Test Case 3
3
4
1,0,0
0,1,0
0,0,1
1,0,0\n
0,1,0\n
0,0,1
1,0,0\n
0,1,0\n
0,0,1\n
Passed after ignoring Presentation Error
Test Case 4
4
3
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
3140,3560,3980,4400\n
7268,8232,9196,10160\n
11396,12904,14412,15920\n
15524,17576,19628,21680
3140,3560,3980,4400\n
7268,8232,9196,10160\n
11396,12904,14412,15920\n
15524,17576,19628,21680\n
Passed after ignoring Presentation Error




Week 7 : Programming Assignment 1

Due on 2025-09-11, 23:59 IST

Problem 1: Image Noise Isolation in Data Analysis

At a medical research lab, image preprocessing involves working with square matrices that represent pixel intensity grids extracted from medical images.

Sometimes, due to faulty sensor data, certain rows and columns must be eliminated to isolate sub-regions of the matrix.

Your task is to implement a function that removes a specified row and column from a square matrix to produce a minor matrix.


Requirements

  1. Function Nameminor_matrix

  2. Parameters:

    • M: A square matrix (list of lists).

    • i: Index of the row to remove (0-based).

    • j: Index of the column to remove (0-based).

  3. Return Value:

    • A new matrix with the i-th row and j-th column removed.

  4. Constraints:

    • The matrix M is always square (n × n).

    • M has at least 3 rows and columns.

    • Indexing is zero-based.

  5. No input/output required — just define the function.


Example

M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] minor_matrix(M, 0, 1) # Expected output: # [[4, 6], # [7, 9]]

Your last recorded submission was on 2025-08-30, 21:28 IST
Select the Language for this assignment. 
1
def minor_matrix(M, i, j):
2
    n = len(M)
3
    result = []
4
    for r in range(n):
5
        if r == i:
6
            continue
7
        new_row = []
8
        for c in range(n):
9
            if c == j:
10
                continue
11
            new_row.append(M[r][c])
12
        result.append(new_row)
13
    return result
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
3
1,2,3
4,5,6
7,8,9
0
1
4,6\n
7,9
4,6\n
7,9\n
Passed after ignoring Presentation Error
Test Case 2
3
1,2,3
4,5,6
7,8,9
2
0
2,3\n
5,6
2,3\n
5,6\n
Passed after ignoring Presentation Error
Test Case 3
3
1,2,3
1,2,3
1,2,3
0
0
2,3\n
2,3
2,3\n
2,3\n
Passed after ignoring Presentation Error
Test Case 4
4
1,2,3,1
2,10,20,4
43,19,98,100
19,48,49,1
2
3
1,2,3\n
2,10,20\n
19,48,49
1,2,3\n
2,10,20\n
19,48,49\n
Passed after ignoring Presentation Error



Week 7 : Programming Assignment 2

Due on 2025-09-11, 23:59 IST

Problem: Generating the IPL Points Table

You are part of the analytics team at the Indian Premier League (IPL) headquarters.
This year, a special edition of the tournament was organized as a round-robin event where each team played exactly one match against every other team. There were no ties — every match resulted in a clear winner and loser.

Eight teams participated in this format:
CSK, DC, KKR, MI, PK, RR, RCB, SH

The tournament officials recorded match outcomes in a specific format. For each team (in a fixed order), they listed the names of the teams it defeated. The lines follow this order:
CSK, DC, KKR, MI, PK, RR, RCB, SH

Example:

CSK,MI,DC,PK

indicates that CSK won against MI, DC, and PK, and lost its remaining matches.

If a line only contains the team’s name (e.g., RCB), it means that team lost all its matches.


Your Task

(a) Process the 8 lines of input and compute the total number of matches won by each team.
(b) Prepare the final IPL points table in descending order of number of wins.
(c) If two or more teams have the same number of wins, sort them in alphabetical order.
(d) Print each entry in the format:

<team name>:<wins>

with no spaces and one entry per line.


Constraints

  • Input always follows the described format.

  • Every team plays exactly 7 matches.

  • No drawn or tied games.


Example Input

CSK,MI,DC,PK DC,MI,SH KKR,CSK,RR MI PK,RR,MI RR,MI RCB,DC SH,PK

Example Output

CSK:3 DC:2 KKR:3 MI:0 PK:2 RR:1 RCB:1 SH:2

Your last recorded submission was on 2025-08-30, 21:38 IST
Select the Language for this assignment. 
1
def solve():
2
    teams = ['CSK', 'DC', 'KKR', 'MI', 'PK', 'RR', 'RCB', 'SH']
3
    wins = {}
4
    for i in range(8):
5
        s = input().strip()
6
        parts = s.split(',')
7
        wins[teams[i]] = len(parts) - 1
8
    sorted_teams = sorted(teams, key=lambda x: (-wins[x], x))
9
    for team in sorted_teams:
10
        print(f"{team}:{wins[team]}")
11
solve()
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
CSK,DC,KKR,MI,PK,RR,RCB,SH
DC,KKR,MI,PK,RR,RCB,SH
KKR,MI,PK,RR,RCB,SH
MI,PK,RR,RCB,SH
PK,RR,RCB,SH
RR,RCB,SH
RCB,SH
SH
CSK:7\n
DC:6\n
KKR:5\n
MI:4\n
PK:3\n
RR:2\n
RCB:1\n
SH:0
CSK:7\n
DC:6\n
KKR:5\n
MI:4\n
PK:3\n
RR:2\n
RCB:1\n
SH:0\n
Passed after ignoring Presentation Error
Test Case 2
CSK,DC,MI,PK
DC,RR,RCB,SH
KKR,CSK,DC,RR,MI
MI,DC,RCB,RR
PK,DC,KKR,MI,RCB
RR,CSK,PK,SH
RCB,CSK,KKR,RR
SH,CSK,KKR,MI,PK,RCB
SH:5\n
KKR:4\n
PK:4\n
CSK:3\n
DC:3\n
MI:3\n
RCB:3\n
RR:3
SH:5\n
KKR:4\n
PK:4\n
CSK:3\n
DC:3\n
MI:3\n
RCB:3\n
RR:3\n
Passed after ignoring Presentation Error
Test Case 3
CSK,RCB,MI,KKR
DC,CSK,KKR,MI,SH
KKR,PK,RR,RCB,SH
MI,KKR,PK,RR,SH,RCB
PK,CSK,DC,RCB
RR,CSK,DC,PK,SH
RCB,DC,RR
SH,CSK,PK,RCB
MI:5\n
DC:4\n
KKR:4\n
RR:4\n
CSK:3\n
PK:3\n
SH:3\n
RCB:2
MI:5\n
DC:4\n
KKR:4\n
RR:4\n
CSK:3\n
PK:3\n
SH:3\n
RCB:2\n
Passed after ignoring Presentation Error
Test Case 4
CSK
DC,CSK,KKR,MI,PK,RR,RCB,SH
KKR,CSK,MI,PK
MI,CSK,PK,RR,SH,RCB
PK,CSK,RCB,SH
RR,CSK,KKR,PK
RCB,CSK,KKR,RR,SH
SH,CSK,KKR,RR
DC:7\n
MI:5\n
RCB:4\n
KKR:3\n
PK:3\n
RR:3\n
SH:3\n
CSK:0
DC:7\n
MI:5\n
RCB:4\n
KKR:3\n
PK:3\n
RR:3\n
SH:3\n
CSK:0\n
Passed after ignoring Presentation Error
Test Case 5
CSK,SH,RCB
DC,CSK,SH
KKR,CSK,DC
MI,CSK,DC,KKR
PK,CSK,DC,KKR,MI
RR,CSK,DC,KKR,MI,PK
RCB,DC,KKR,MI,PK,RR
SH,KKR,MI,PK,RR,RCB
RCB:5\n
RR:5\n
SH:5\n
PK:4\n
MI:3\n
CSK:2\n
DC:2\n
KKR:2
RCB:5\n
RR:5\n
SH:5\n
PK:4\n
MI:3\n
CSK:2\n
DC:2\n
KKR:2\n
Passed after ignoring Presentation Error



Week 7 : Programming Assignment 3

Due on 2025-09-11, 23:59 IST

Problem Statement: Symmetric Double Pyramid Pattern

Objective:
Write a program to print a symmetric star pattern based on a given integer input n.


 Input:

  • A single integer n (1 ≤ n ≤ 100), representing the number of rows in the upper half of the pattern.


Output:

  • Print a pattern consisting of 2n - 1 rows.

  • Each row should contain stars and spaces arranged symmetrically according to the value of n.


Example:

Input:

4

Output:

*      *
**    **
***  ***
********
***  ***
**    **
*      *


Your last recorded submission was on 2025-08-30, 21:37 IST
Select the Language for this assignment. 
1
def pattern(n):
2
    total_rows = 2 * n - 1
3
    for i in range(1, total_rows + 1):
4
        if i <= n:
5
            stars = i
6
            spaces = 2 * (n - i)
7
        else:
8
            stars = 2 * n - i
9
            spaces = 2 * (i - n)
10
        print('*' * stars + ' ' * spaces + '*' * stars)
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
4
*      *\n
**    **\n
***  ***\n
********\n
***  ***\n
**    **\n
*      *
*      *\n
**    **\n
***  ***\n
********\n
***  ***\n
**    **\n
*      *\n
Passed after ignoring Presentation Error
Test Case 2
2
*  *\n
****\n
*  *
*  *\n
****\n
*  *\n
Passed after ignoring Presentation Error
Test Case 3
3
*    *\n
**  **\n
******\n
**  **\n
*    *
*    *\n
**  **\n
******\n
**  **\n
*    *\n
Passed after ignoring Presentation Error





Week 8: Programming Assignment 1

Due on 2025-09-18, 23:59 IST

Problem Statement

You have a locker containing a number of coins. Each coin has a positive integer value engraved on it, representing its worth. You are required to determine whether it is possible to withdraw a subset of these coins such that their combined value is exactly equal to a target amount.


Function Specification

Write a recursive function named subset_sum that takes the following arguments:

  • L – a list of positive integers, where each integer represents the value of a coin.

  • s – a positive integer representing the target value.

The function should return True if it is possible to choose a subset of coins from the list whose sum is exactly s, and False otherwise.


Constraints

  • The list L may be empty.

  • No loops or libraries that generate all subsets may be used.

  • The solution must be recursive.

Your last recorded submission was on 2025-09-17, 10:02 IST
Select the Language for this assignment. 
1
def subset_sum(L, s):
2
    if s == 0:
3
        return True
4
    if not L:
5
        return False
6
    if L[0] > s:
7
        return subset_sum(L[1:], s)
8
    return subset_sum(L[1:], s - L[0]) or subset_sum(L[1:], s)
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
subset_sum([2, 4, 6], 6)
True
True\n
Passed after ignoring Presentation Error
Test Case 2
subset_sum([1, 3, 5, 7], 10)
True
True\n
Passed after ignoring Presentation Error
Test Case 3
subset_sum([5, 10, 12], 3)
False
False\n
Passed after ignoring Presentation Error
Test Case 4
subset_sum([], 0)
True
True\n
Passed after ignoring Presentation Error




Week 8: Programming Assignment 2

Due on 2025-09-18, 23:59 IST
Collatz Function
The Collatz function is defined for any positive integer n as:
                       
                       f(n)  =       3n + 1 , if n is odd
                                        n / 2    , if n is even

We repeatedly apply the function f starting from an integer n, producing a sequence:
                                   f(n), f(f(n)), f(f(f(n))), . . .

It is believed (but not proven) that no matter which positive number you start with, this sequence will always eventually reach 1.

Example:

If n = 10, the sequence is:

10 → 5 → 16 → 8 → 4 → 2 → 1

Starting at n = 10, we must apply the function f six times to reach 1.


Your Task

Write a recursive function named collatz that:

  • Accepts a positive integer n such that: 1 < n ≤ 32,000

  • Returns the number of times the function f needs to be applied to reach 1.


Requirements

  • Do not print anything or take input from the user.

  • Only write the function definition.

  • Use recursion in your solution.

Your last recorded submission was on 2025-09-17, 10:04 IST
Select the Language for this assignment. 
1
def collatz(n):
2
    if n == 1:
3
        return 0
4
    if n % 2 == 0:
5
        return 1 + collatz(n // 2)
6
    else:
7
        return 1 + collatz(3 * n + 1)
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
collatz(10)
6
6\n
Passed after ignoring Presentation Error
Test Case 2
collatz(1)
0
0\n
Passed after ignoring Presentation Error
Test Case 3
collatz(3)
7
7\n
Passed after ignoring Presentation Error
Test Case 4
collatz(6)
8
8\n
Passed after ignoring Presentation Error




Week 8: Programming Assignment 3

Due on 2025-09-18, 23:59 IST

Problem: Twin Primes

Two numbers p and q are said to be twin primes if:

  1. Both p and q are prime numbers, and

  2. The absolute difference between them is 2, i.e., |p − q| = 2.


Task

Write a function twin_primes(p, q) that:

  • Accepts two integers p and q as arguments,

  • Returns True if they are twin primes, and False otherwise.

      Note:

  • The function should not print anything.

  • The function should not accept input from the user.You may use helper functions if needed.

  • You only need to write the function definition.  .       
Your last recorded submission was on 2025-09-17, 10:06 IST
Select the Language for this assignment. 
1
def twin_primes(p, q):
2
    def is_prime(n):
3
        if n <= 1:
4
            return False
5
        for i in range(2, int(n**0.5) + 1):
6
            if n % i == 0:
7
                return False
8
        return True
9
    if is_prime(p) and is_prime(q) and abs(p - q) == 2:
10
        return True
11
    else:
12
        return False
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
twin_primes(5, 7)
True
True\n
Passed after ignoring Presentation Error
Test Case 2
twin_primes(11, 13)
True
True\n
Passed after ignoring Presentation Error
Test Case 3
twin_primes(17, 19)
True
True\n
Passed after ignoring Presentation Error
Test Case 4
twin_primes(5, 6)
False
False\n
Passed after ignoring Presentation Error






Week 9 : Programming Assignment 1

Due on 2025-09-25, 23:59 IST

Problem Statement: Merge Two Dictionaries

Write a function named merge that merges two dictionaries D1 and D2 into a new dictionary D following these rules:

  1. Each key-value pair in D must come from either D1 or D2.

  2. Every key from both D1 and D2 must be present in D.

  3. If a key appears in both D1 and D2, the value to retain depends on the argument priority:

    • If priority is "first", retain the value from D1.

    • If priority is "second", retain the value from D2.

  4. All keys in the resulting dictionary D must be sorted in alphabetical order.

Constraints:

  • Do not print anything.

  • Do not accept input from the user. Only define the function.

Your last recorded submission was on 2025-09-20, 18:11 IST
Select the Language for this assignment. 
1
def merge(D1, D2, priority):
2
    if priority == "first":
3
        merged_temp = {**D2, **D1}
4
    else:
5
        merged_temp = {**D1, **D2}
6
    sorted_keys = sorted(merged_temp.keys())
7
    final_dict = {key: merged_temp[key] for key in sorted_keys}
8
    return final_dict
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
merge({'a': 1, 'b': 2}, {'b': 3, 'c': 4}, "first")
{'a': 1, 'b': 2, 'c': 4}
{'a': 1, 'b': 2, 'c': 4}\n
Passed after ignoring Presentation Error
Test Case 2
merge({'x': 10}, {'x': 20, 'y': 30}, "second")
{'x': 20, 'y': 30}
{'x': 20, 'y': 30}\n
Passed after ignoring Presentation Error
Test Case 3
merge({'k': 5, 'm': 6}, {'n': 7, 'm': 8}, "first")
{'k': 5, 'm': 6, 'n': 7}
{'k': 5, 'm': 6, 'n': 7}\n
Passed after ignoring Presentation Error
Test Case 4
merge({'p': 1}, {'q': 2}, "second")
{'p': 1, 'q': 2}
{'p': 1, 'q': 2}\n
Passed after ignoring Presentation Error



Week 9 : Programming Assignment 2

Due on 2025-09-25, 23:59 IST

Problem Statement

You are given a 2-dimensional list mat that represents a matrix.

Write a function rotate(mat) that returns a new matrix rotated 90° clockwise.

  • The input mat is a list of lists, where each inner list represents a row.

  • You do not need to handle input/output.

Hint / Approach:

  1. First, compute the transpose of the matrix.

  2. Then, reverse each row of the transposed matrix.

Your last recorded submission was on 2025-09-20, 18:12 IST
Select the Language for this assignment. 
1
def rotate(mat):
2
    if not mat or not mat[0]:
3
        return []
4
    transposed = list(zip(*mat))
5
    rotated = [list(row)[::-1] for row in transposed]
6
    return rotated
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
[[1,2,3],[4,5,6]]
[[4, 1], [5, 2], [6, 3]]
[[4, 1], [5, 2], [6, 3]]\n
Passed after ignoring Presentation Error
Test Case 2
[[7,8],[9,10],[11,12]]
[[11, 9, 7], [12, 10, 8]]
[[11, 9, 7], [12, 10, 8]]\n
Passed after ignoring Presentation Error
Test Case 3
[[1]]
[[1]]
[[1]]\n
Passed after ignoring Presentation Error
Test Case 4
[[1,2],[3,4]]
[[3, 1], [4, 2]]
[[3, 1], [4, 2]]\n
Passed after ignoring Presentation Error



Week 9 : Programming Assignment 3

Due on 2025-09-25, 23:59 IST

Problem Statement

You are working on a text analysis tool that groups words based on their frequency in a given list. For example, you might want to find all words that appear exactly once, all words that appear twice, and so on.

Write a function freq_to_words that accepts a list of lowercase words as input and returns a dictionary with the following structure:

  • Key: Frequency (positive integer) of the words

  • Value: List of all words that occur exactly that many times in the input

You do not need to accept any input from the user or print anything to the console. Just write the function definition.

Your last recorded submission was on 2025-09-20, 18:13 IST
Select the Language for this assignment. 
1
def freq_to_words(words):
2
    word_counts = {}
3
    for word in words:
4
        word_counts[word] = word_counts.get(word, 0) + 1
5
    freq_dict = {}
6
    for word, count in word_counts.items():
7
        if count not in freq_dict:
8
            freq_dict[count] = []
9
        freq_dict[count].append(word)
10
    return freq_dict
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
['a', 'random', 'collection', 'a', 'another', 'a', 'random']
{3: ['a'], 2: ['random'], 1: ['collection', 'another']}
{3: ['a'], 2: ['random'], 1: ['collection', 'another']}\n
Passed after ignoring Presentation Error
Test Case 2
['one', 'two', 'three', 'one']
{2: ['one'], 1: ['two', 'three']}
{2: ['one'], 1: ['two', 'three']}\n
Passed after ignoring Presentation Error
Test Case 3
['x', 'x', 'y', 'z', 'y', 'x']
{3: ['x'], 2: ['y'], 1: ['z']}
{3: ['x'], 2: ['y'], 1: ['z']}\n
Passed after ignoring Presentation Error
Test Case 4
['apple']
{1: ['apple']}
{1: ['apple']}\n
Passed after ignoring Presentation Error





Week 10 : Programming Assignment 1

Due on 2025-10-02, 23:59 IST

Problem Statement

You are working with a dataset named scores_dataset, which is a list of dictionaries.
Each dictionary contains information about a student’s name, gender, city, and their scores in various subjects.

Example entry:

{ 'SeqNo': 1, 'Name': 'Devika', 'Gender': 'F', 'City': 'Bengaluru', 'Mathematics': 85, 'Physics': 100, 'Chemistry': 79, 'Biology': 75, 'Computer Science': 88, 'History': 60, 'Civics': 88, 'Philosophy': 95 }

Two students X and Y are said to be in a mentorship relation in a given subject if:

10 ≤ X.subject − Y.subject ≤ 20

That is, student X can mentor student Y in a subject if their score difference lies between 10 and 20 (inclusive) and X’s score is higher.

Constraints:

  • A student cannot mentor themselves.

  • If a student cannot mentor anyone, the list should be empty.


Function Signature

Write a function named mentors that accepts:

  • scores_dataset: a list of student records

  • subject: a string representing the subject

The function should return a dictionary:

  • KeySeqNo of a student

  • Value: List of SeqNo values of students that can be mentored by this student in the given subject


Your last recorded submission was on 2025-09-25, 17:20 IST
Select the Language for this assignment. 
1
def mentors(scores_dataset, subject):
2
    mentorships = {}
3
    for mentorG in scores_dataset:
4
        mentor_seq = mentorG['SeqNo']
5
        mentor_score = mentorG.get(subject)
6
        mentees = []
7
        for mentee in scores_dataset:
8
            mentee_seq = mentee['SeqNo']
9
            mentee_score = mentee.get(subject)
10
            if mentor_seq != mentee_seq:
11
                diff = mentor_score - mentee_score
12
                if 10 <= diff <= 20:
13
                    mentees.append(mentee_seq)
14
        mentorships[mentor_seq] = mentees
15
    return mentorships
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
[{'SeqNo': 1, 'Name': 'A', 'Mathematics': 90}, {'SeqNo': 2, 'Name': 'B', 'Mathematics': 80}, {'SeqNo': 3, 'Name': 'C', 'Mathematics': 70}, {'SeqNo': 4, 'Name': 'D', 'Mathematics': 75}, {'SeqNo': 5, 'Name': 'E', 'Mathematics': 60}]
Mathematics
{1: [2, 3, 4], 2: [3, 5], 3: [5], 4: [5], 5: []}
{1: [2, 3, 4], 2: [3, 5], 3: [5], 4: [5], 5: []}\n
Passed after ignoring Presentation Error
Test Case 2
[{'SeqNo': 1, 'Name': 'A', 'Physics': 95}, {'SeqNo': 2, 'Name': 'B', 'Physics': 85}, {'SeqNo': 3, 'Name': 'C', 'Physics': 65}]
Physics
{1: [2], 2: [3], 3: []}
{1: [2], 2: [3], 3: []}\n
Passed after ignoring Presentation Error
Test Case 3
[{'SeqNo': 1, 'Name': 'A', 'Biology': 92}, {'SeqNo': 2, 'Name': 'B', 'Biology': 81}, {'SeqNo': 3, 'Name': 'C', 'Biology': 72}, {'SeqNo': 4, 'Name': 'D', 'Biology': 62}]
Biology
{1: [2, 3], 2: [4], 3: [4], 4: []}
{1: [2, 3], 2: [4], 3: [4], 4: []}\n
Passed after ignoring Presentation Error



Week 10 : Programming Assignment 2

Due on 2025-10-02, 23:59 IST

IIT Ropar has a campus store called RoparMart. Each transaction is recorded as a dictionary with:

  • "TID": Unique transaction ID (string)

  • "Items": List of dictionaries for each item with:

    • "Name": Name of the item

    • "Price": Price per unit

    • "Qty": Quantity purchased

Task: Write a function get_summary(trans) that computes the total cost of each transaction and returns a summary list.

Function Signature:

def get_summary(trans):

Your last recorded submission was on 2025-09-25, 17:21 IST
Select the Language for this assignment. 
1
def get_summary(trans):
2
    summary_list = []
3
    for transaction in trans:
4
        total_cost = 0
5
        tid = transaction['TID']
6
        items = transaction['Items']
7
        for item in items:
8
            total_cost += item['Price'] * item['Qty']
9
        summary_list.append({'TID': tid, 'Cost': total_cost})
10
    return summary_list
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
[{"TID": "RoparMart_1001", "Items": [{"Name": "Notebook", "Price": 50, "Qty": 4}, {"Name": "Pencil", "Price": 10, "Qty": 1}, {"Name": "Eraser", "Price": 15, "Qty": 1}, {"Name": "File", "Price": 80, "Qty": 1}]}]
[{'TID': 'RoparMart_1001', 'Cost': 305}]
[{'TID': 'RoparMart_1001', 'Cost': 305}]\n
Passed after ignoring Presentation Error
Test Case 2
[{"TID": "RoparMart_1002", "Items": [{"Name": "Pen", "Price": 20, "Qty": 2}, {"Name": "Scale", "Price": 30, "Qty": 1}]}]
[{'TID': 'RoparMart_1002', 'Cost': 70}]
[{'TID': 'RoparMart_1002', 'Cost': 70}]\n
Passed after ignoring Presentation Error



Week 10 : Programming Assignment 3

Due on 2025-10-02, 23:59 IST

Problem Statement: Run-Length Encoding for Hostel Notice Board

The hostel manager at IIT Ropar maintains a digital notice board accessible to all students. Notices are uploaded as plain text, but as the number of notices grows, server space usage increases.

To reduce storage, the IT admin wants a basic compression algorithm that can shrink repetitive characters in each notice.

Compression Logic

The admin proposes using a simple form of Run-Length Encoding (RLE):

  • Consecutive repetitions of a character are replaced with the character followed by the count of its occurrences.

  • If a character appears only once consecutively, it remains unchanged.

Example:

"aaabbc""a3b2c"

Task

Write a function compress that accepts a string notice and returns its compressed form using the above RLE logic.

Function Signature:

def compress(notice):

Instructions

  • You do not need to accept input from the user or print output to the console.

  • All characters in the string will be lowercase letters.

  • The length of the string will be between 1 and 1000.


Your last recorded submission was on 2025-09-25, 17:22 IST
Select the Language for this assignment. 
1
def compress(notice):
2
    notice = notice.strip()
3
    compressed_string = ""
4
    if not notice:
5
        return compressed_string
6
    i = 0
7
    while i < len(notice):
8
        current_char = notice[i]
9
        count = 1
10
        j = i + 1
11
        while j < len(notice) and notice[j] == current_char:
12
            count += 1
13
            j += 1
14
        compressed_string += current_char
15
        if count > 1:
16
            compressed_string += str(count)
17
        i = j
18
    return compressed_string
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
" aaabccddddee "
a3bc2d4e2
a3bc2d4e2\n
Passed after ignoring Presentation Error
Test Case 2
" abc "
abc
abc\n
Passed after ignoring Presentation Error































































No comments:

Post a Comment

Keep your comments reader friendly. Be civil and respectful. No self-promotion or spam. Stick to the topic. Questions welcome.