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 Jan-2024 Week 9 to 10 | Swayam

NPTEL The Joy of Computing using Python Jan-2024 Week 9 to 10 | Swayam

 

  Please scroll down for latest Programs ðŸ‘‡ 


1. Programming Assignment | Week 9

Due on 2024-03-28, 23:59 IST

word is a string that contains one or more parentheses of the following types: "{ }", "[ ]", "( )". The string is said to be balanced if all the following conditions are satisfied.

When read from left to right:
(1) The number of opening parentheses of a given type is equal to the number of closing parentheses of the same type.
(2) An opening parenthesis cannot be immediately followed by a closing parenthesis of a different type.
(3) Every opening parenthesis should be eventually closed by a closing parenthesis of the same type.


Write a function named balanced that accepts the string word as an argument. Return True if the string is balanced, and False otherwise. You can assume that the string doesn't contain any characters other than parentheses.


You do not have to accept the input from the user or print output to the console. You just have to write the function definition.

 

Your last recorded submission was on 2024-03-20, 23:43 IST
Select the Language for this assignment. 
1
def balanced(word):
2
    """
3
    Determine if a string is balanced
4
    Argument:
5
        word: string
6
    Return:
7
        result: bool
8
    """
9
    Braces, Brackets, Parentheses = 0, 0, 0
10
    if word[0] == '{':
11
      Braces+=1
12
    elif word[0] == '[':
13
      Brackets+=1
14
    elif word[0] == '(':
15
      Parentheses+=1
16
    else :
17
      return False
18
    x = 1
19
    for i in range(1,len(word)):
20
      if word[i] == '{':
21
        Braces+=1
22
      elif word[i] == '[':
23
        Brackets+=1
24
      elif word[i] == '(':
25
        Parentheses+=1
26
      elif word[i] == '}':
27
        if word[i-x] == '{':
28
          Braces-=1
29
          x+=2
30
        else:
31
          return False
32
      elif word[i] == ')':
33
        if word[i-x] == '(':
34
          Parentheses-=1
35
          x+=2
36
        else:
37
          return False
38
      elif word[i] == ']':
39
        if word[i-x] == '[':
40
          Brackets-=1
41
          x+=2
42
        else:
43
          return False
44
      
45
    if (Braces, Brackets, Parentheses) == (0, 0, 0):
46
      return True
47
    else:
48
      return False
49
    
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
([{}])
True
True\n
Passed after ignoring Presentation Error
Test Case 2
[(])
False
False\n
Passed after ignoring Presentation Error
Test Case 3
)([]
False
False\n
Passed after ignoring Presentation Error



2. Programming Assignment | Week 9

Due on 2024-03-28, 23:59 IST

Consider the problem about balanced expressions discussed in 1. Programming Assignment | Week 9. We have a balanced expression (string) that has only the flower brackets: '( )'. We can recursively define a concept called nesting depth for each pair of opening and closing brackets.

The nesting depth of a pair that lies within another pair is one more than the nesting depth of the pair that immediately englobes it. For a pair that is not surrounded by any other pair, the nesting depth is 1.


 Write a function named depth that accepts a balanced expression (string) as an argument. It should return the maximum nesting depth in this expression.


You do not have to accept the input from the user or print output to the console. You just have to write the function definition.

Your last recorded submission was on 2024-03-21, 09:24 IST
Select the Language for this assignment. 
1
def depth(exp):
2
    """
3
    Compute the maximum nesting depth
4
    
5
    Argument:
6
        exp: string
7
    Return:
8
        result: integer
9
    """
10
    max_nest = 0
11
    Open_Bracket = 0
12
    Close_Bracket = 0
13
    for i in exp:
14
      if i == '(':
15
        Open_Bracket+=1
16
      elif i == ')':
17
        if Open_Bracket > max_nest:
18
          max_nest = Open_Bracket
19
        Open_Bracket-=1
20
    return max_nest
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
2\n
Passed after ignoring Presentation Error
Test Case 2
(()(()))()
3
3\n
Passed after ignoring Presentation Error



3. Programming Assignment | Week 9

Due on 2024-03-28, 23:59 IST

Write a recursive function named power that accepts a square matrix A and a positive integer m as arguments and returns Am.


You do not have to accept input from the user or print the output to the console. You just have to write the function definition.

Your last recorded submission was on 2024-03-21, 09:25 IST
Select the Language for this assignment. 
1
def power(A, m):
2
    """
3
    A recursive function to compute A ** m
4
5
    Arguments:
6
        A: list of lists
7
        m: integer
8
    Return:
9
        result: list of lists
10
    """
11
    if m == 1:
12
      return A
13
    else:
14
      n = len(A)
15
      B = power(A,m-1)
16
      C = []
17
      for i in range(n):
18
        row = []
19
        for j in range(n):
20
          sum = 0
21
          for k in range(n):
22
            sum += int(A[i][k]) * int(B[k][j])
23
          row += [sum]
24
        C+=[row]
25
      return C
26
    
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







1. Programming Assignment | Week 10

Due on 2024-04-11, 23:59 IST
Write a function named rotate that accepts a matrix mat as argument. It should return a matrix that is rotated by 90 degrees in the clockwise direction. For example:

You do not have to accept input from the user or print output to the console. You just have to write the function definition.

Your last recorded submission was on 2024-03-26, 17:41 IST
Select the Language for this assignment. 
1
def rotate(mat):
2
    """
3
    Rotate a matrix 90 degrees clockwise
4
    
5
    Argument:
6
        mat: list of lists
7
    Return:
8
        rotated_mat: list of lists
9
    """
10
    rotated_mat=[]
11
    c=len(mat[0])
12
    r=len(mat)
13
    for i in range(0,c):
14
      li=[]
15
      for j in range(r-1,-1,-1):
16
        li=li+[mat[j][i]]
17
      rotated_mat=rotated_mat+[li] 
18
    return(rotated_mat)
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
1,2,3
4,5,6
4,1\n
5,2\n
6,3
4,1\n
5,2\n
6,3\n
Passed after ignoring Presentation Error
Test Case 2
3,2
1,2
3,4
5,6
5,3,1\n
6,4,2
5,3,1\n
6,4,2\n
Passed after ignoring Presentation Error
Test Case 3
3,3
1,2,3
4,5,6
7,8,9
7,4,1\n
8,5,2\n
9,6,3
7,4,1\n
8,5,2\n
9,6,3\n
Passed after ignoring Presentation Error





2. Programming Assignment | Week 10

Due on 2024-04-11, 23:59 IST
A n×n square matrix of positive integers is called a magic square if the following sums are equal:
(1) row-sum: sum of numbers in every row; there are n such values, one for each row
(2) column-sum: sum of numbers in every column; there are n such values, one for each column
(3) diagonal-sum: sum of numbers in both the diagonals; there are two values

There are n+n+2=2n+2 values involved. All these values must be the same for the matrix to be a magic-square.

Write a function named is_magic that accepts a square matrix as argument and returns YES if it is a magic-square and NO if it isn't one.

Notes

(1) The cells of a magic square need not be distinct. Some or even all the cells could be identical.

(2) You do not have to accept input from the user or print output to the console. You just have to write the function definition.
Your last recorded submission was on 2024-03-26, 17:41 IST
Select the Language for this assignment. 
1
def is_magic(matrix):
2
    """
3
    determine if a matrix is magic square
4
5
    Argument:
6
        mat: list of lists
7
    Return:
8
        string: 'YES' or 'NO'
9
    """
10
    value=0
11
    for i in range(0,len(matrix)):
12
      value+= matrix[0][i]
13
    for i in range(0,len(matrix)):
14
      total = 0
15
      for j in range(0,len(matrix)):
16
        total+=matrix[i][j]
17
      if total != value:
18
        return('NO')
19
    for j in range(0,len(matrix)):
20
      total = 0
21
      for i in range(0,len(matrix)):
22
        total+=matrix[i][j]
23
      if total != value:
24
        return('NO')
25
    total = 0
26
    for i in range(0,len(matrix)):
27
      for j in range(0,len(matrix)):
28
        if i==j:
29
          total+=matrix[i][j]
30
    if total != value:
31
      return('NO')
32
    return('YES')
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
1 2
2 1
NO
NO\n
Passed after ignoring Presentation Error
Test Case 2
3
4 9 2
3 5 7
8 1 6
YES
YES\n
Passed after ignoring Presentation Error






3. Programming Assignment | Week 10

Due on 2024-04-11, 23:59 IST

You are given certain details of the trains that stop at a station. Your task is to store these details in a nested dictionary.


The first line of input is n, the number of trains that stop at the station. n blocks of input follow. The first line in each block corresponds to the train name. The second line in each block corresponds to m, the number of compartments in the train. m lines of input follow. Each of these m lines has two values separated by a comma: name of the compartment and number of passengers in it.


Your task is to create a nested dictionary named station_dict. The keys of the dictionary are train names, the value corresponding to a key is another dictionary. The keys of the inner dictionary are the compartment names in this train, the values are the number of passengers in each compartment. For example:

{
    'Mumbai Express': {
        'S1': 10,
        'S2': 20,
        'S3': 30
    },
    'Chennai Express': {
        'S1': 10,
        'S2': 20,
        'S3': 30
    }
  }

(1) The values of the compartments should be represented as integers and not as strings.
(2) You do not have to print the output to the console. Do not try to print the output that you observe in the "Expected Output". You just have to process the input and create the dictionary station_dict.

Your last recorded submission was on 2024-03-26, 17:54 IST
Select the Language for this assignment. 
1
n = int(input())
2
station_dict = {}
3
for i in range(n):
4
  train = input()
5
  compts = int(input())
6
  compt_dict = {}
7
  for j in range(compts):
8
    l = input().split(',')
9
    compt_dict[l[0]] = int(l[1])
10
  station_dict[train] = compt_dict
11
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
Mumbai Express
2
S1,10
S2,20
Chennai Express
3
S1,5
S2,10
S3,15
{'Mumbai Express': {'S1': 10, 'S2': 20}, 'Chennai Express': {'S1': 5, 'S2': 10, 'S3': 15}}
{'Mumbai Express': {'S1': 10, 'S2': 20}, 'Chennai Express': {'S1': 5, 'S2': 10, 'S3': 15}}\n
Passed after ignoring Presentation Error
Test Case 2
1
Rajdhani Express
5
S1,1
S2,2
S3,10
S4,20
S5,20
{'Rajdhani Express': {'S1': 1, 'S2': 2, 'S3': 10, 'S4': 20, 'S5': 20}}
{'Rajdhani Express': {'S1': 1, 'S2': 2, 'S3': 10, 'S4': 20, 'S5': 20}}\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.