# [Week 1 to 8] NPTEL Programming, Data Structures And Algorithms Using Python Assignment Answers 2023 NPTEL Programming, Data Structures And Algorithms Using Python Assignment Solutions 2023

## Programming, Data Structures And Algorithms Using Python Week 8 Quiz Assignment Answers 2023

### Dividing Sequences

This problem is about sequences of positive integers a1,a2,…,aN. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, 3,7,11,3 is a subsequence of 6,3,11,5,7,4,3,11,5,3 , but 3,3,7 is not a subsequence of 6,3,11,5,7,4,3,11,5,3 .

fully dividing sequence is a sequence a1,a2,…,aN where ai divides aj whenever i < j. For example, 3,15,60,720 is a fully dividing sequence.

Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence.

Consider the sequence 2,3,7,8,14,39,145,76,320

It has a fully dividing sequence of length 3, namely 2,8,320, but none of length 4 or greater.

Consider the sequence 2,11,16,12,36,60,71,17,29,144,288,129,432,993 .

It has two fully dividing subsequences of length 5,

• 2,11,16,12,36,60,71,17,29,144,288,129,432,993 and
• 2,11,16,12,36,60,71,17,29,144,288,129,432,993

and none of length 6 or greater.

### Solution hint

Let the input be a1, a2, …, aN. Let us define Best(i) to be the length of longest dividing sequence in a1,a2,…ai that includes ai.

Write an expression for Best(i) in terms of Best(j) with j<i, with base case Best(1) = 1. Solve this recurrence using dynamic programming.

Solution:-

```n = int(input())
L = list()
bestvals =list()
best_stored = list()
for x in range(n):
L.append(int(input()))
best_stored.append(0)

best_stored = 1

for i in range(n):
maxval = 1
for j in range(i):
if L[i] % L[j] == 0:
maxval = max(maxval,(best_stored[j])+1)
best_stored[i] = maxval

print(max(best_stored),end="")```

## Programming, Data Structures And Algorithms Using Python Week 7 Quiz Assignment Answers 2023

1. Given the following permutation of a,b,c,d,e,f,g,h,i,j, what is the next permutation in lexicographic (dictionary) order? Write your answer as a sequence of letters without quotes and without any blank spaces between letters.

eibjdhgfca

```Answer :- (Type: Regex Match) [ ]*eibjfacdgh[ ]*
(Type: Regex Match) [ ]*\'eibjfacdgh\'[ ]*
(Type: Regex Match) [ ]*\"eibjfacdgh\"[ ]*```

2. We want to add a function listmax() to the class Node that implements user defined lists such that listmax() computes the maximum value in a list where values are of type int.

An incomplete implementation of listmax() given below. You have to provide expressions to put in place of AAA, BBB and CCC.

`````` def listmax(self):
if self.value == None:
return(AAA)
elif self.next == None:
return(BBB)
else:
return(CCC)``````

AAA: 0, BBB: self.value, CCC: max(self.value, self.next.listmax())
AAA: 0, BBB: self.value, CCC: max(self.value, self.next.value)
AAA: None, BBB: self.value, CCC: max(self.value, self.next.listmax())
AAA: None, BBB: self.value, CCC: max(self.value, self.next.value)

`Answer :- c`

3. Suppose we add this function foo() to the class Tree that implements search trees. For a name mytree with a value of type Tree, what would mytree.foo() compute?

``````def foo(self):
if self.isempty():
return(0)
elif self.isleaf():
return(1)
else:
return(self.left.foo() + self.right.foo())``````

The number of nodes in mytree
The largest value in mytree.
The length of the longest path from root to leaf in mytree.
The number of leaves in mytree.

`Answer :- d`

4. Inorder traversal of a binary tree has been defined in the lectures. A postorder traversal lists the vertices of a binary tree (not necessarily a search tree) as

follows:
Print the left subtree in postorder.
Print the right subtree in postorder.
Print the root.

Suppose we have a binary tree with 10 nodes labelled a, b, c, d, e, f, g, h, i, j, with postorder traversal ehicbjfadg and inorder traversal ehbicgjafd. What is the left child of the root node? (Write your answer as a single letter, without quotes.)

`Answer :- b       (Type it)`

## Programming, Data Structures And Algorithms Using Python Week 6 Quiz Assignment Answers 2023

1. Suppose u and v both have values of type set and are disjoint. Which of the following expressions evaluates to True?
u == v | (u^v)
u == (v^u)
u == v^(u | v)
u == u^(v | u)

`Answer :- c`

2. Suppose u and v both denote sets in Python. What is the most general condition that guarantees that u|v == u^v?
The sets u and v should be disjoint.
The set u should be a subset of the set v.
The set v should be a subset of the set u.
This is true for any u and v.

`Answer :- a`

3. Consider the min-heap [15, 27, 33, 39, 66, 39, 47, 58, 51]. built by repeatedly inserting values into an empty heap. Which of the following could not have been the last element inserted into this heap?
27
15
58
51

`Answer :- c`

4. Consider the min-heap [13, 24, 32, 32, 41, 38, 50, 48, 40] built by repeatedly inserting values into an empty heap. Suppose the last value inserted was 24. What was the heap structure before this value was inserted?
[13, 32, 32, 41, 40, 38, 50, 48]
[13, 41, 32, 40, 32, 38, 50, 48]
[13, 32, 32, 48, 41, 38, 50, 40]
[13, 32, 32, 40, 41, 38, 50, 48]

`Answer :- d`

## Programming, Data Structures And Algorithms Using Python Week 5 Programming Assignment Answers 2023

Q1. For this assignment, you have to write a complete Python program. Paste your code in the window below.

• You may define additional auxiliary functions as needed.
• In all cases you may assume that the input to your program has the expected format, so your program does not have to check for malformed inputs.
• There are some public test cases and some (hidden) private test cases.
• “Compile and run” will evaluate your submission against the public test cases.
• “Submit” will evaluate your submission against the hidden private test cases. There are 6 private test cases, with equal weightage. You will get feedback about which private test cases pass or fail, though you cannot see the actual test cases.
• Ignore warnings about “Presentation errors”.

The academic office at the Hogwarts School of Witchcraft and Wizardry has compiled data about students’ grades. The data is provided as text from standard input in three parts: information about courses, information about students and information about grades. Each part has a specific line format, described below..

Line format: Course Code~Course Name~Semester~Year~Instructor
Line format: Roll Number~Full Name

The possible grades are A, AB, B, BC, C, CD, D with corresponding grade points 10, 9, 8, 7, 6, 5 and 4. The grade point average of a student is the sum of his/her grade points divided by the number of courses. For instance, if a student has taken two courses with grades A and C, the grade point average is 8.50 = (10+7)÷2. If a student has not completed any courses, the grade point average is defined to be 0.

You may assume that the data is internally consistent. For every grade, there is a corresponding course code and roll number in the input data.

Each section of the input starts with a line containing a single keyword. The first section begins with a line containing Courses. The second section begins with a line containing Students. The third section begins with a line containing Grades. The end of the input is marked by a line containing EndOfInput.

Write a Python program to read the data as described above and print out a line listing the grade point average for each student in the following format:Roll Number~Full Name~Grade Point Average

Your output should be sorted by Roll Number. The grade point average should be rounded off to 2 digits after the decimal point. Use the built-in function round().

Here is a sample input and its corresponding output.

Sample InputCourses TRAN~Transfiguration~1~2011-2012~Minerva McGonagall CHAR~Charms~1~2011-2012~Filius Flitwick Students SLY2301~Hannah Abbott SLY2302~Euan Abercrombie SLY2303~Stewart Ackerley SLY2304~Bertram Aubrey SLY2305~Avery SLY2306~Malcolm Baddock SLY2307~Marcus Belby SLY2308~Katie Bell SLY2309~Sirius Orion Black Grades TRAN~1~2011-2012~SLY2301~AB TRAN~1~2011-2012~SLY2302~B TRAN~1~2011-2012~SLY2303~B TRAN~1~2011-2012~SLY2305~A TRAN~1~2011-2012~SLY2306~BC TRAN~1~2011-2012~SLY2308~A TRAN~1~2011-2012~SLY2309~AB CHAR~1~2011-2012~SLY2301~A CHAR~1~2011-2012~SLY2302~BC CHAR~1~2011-2012~SLY2303~B CHAR~1~2011-2012~SLY2305~BC CHAR~1~2011-2012~SLY2306~C CHAR~1~2011-2012~SLY2307~B CHAR~1~2011-2012~SLY2308~AB EndOfInput

Sample OutputSLY2301~Hannah Abbott~9.5 SLY2302~Euan Abercrombie~7.5 SLY2303~Stewart Ackerley~8.0 SLY2304~Bertram Aubrey~0 SLY2305~Avery~8.5 SLY2306~Malcolm Baddock~6.5 SLY2307~Marcus Belby~8.0 SLY2308~Katie Bell~9.5 SLY2309~Sirius Orion Black~9.0

### Solution:-

```def Gvalue(code1):
if code1=="A":
return(10)
if code1=="AB":
return(9)
if code1=="B":
return(8)
if code1=="BC":
return(7)
if code1=="C":
return(6)
if code1=="CD":
return(5)
if code1=="D":
return(4)

# varibles used for storing data

Roll_course_count={}
Roll_name={}

#COURSES INPUT SECTION

type_course=input()
enter_course_detail=input()
next_input=input()
while(next_input!="Students"):
next_input=input()

#STUDENT INPUT SECTION

#if it fails in courses section then
#it will automatically enter students

roll,name=input().split('~')
Roll_name[roll]=name
Roll_course_count[roll]=0
next_input=input()
while('~' in next_input):
roll,name=next_input.split('~')
Roll_name[roll]=name
Roll_course_count[roll]=0
next_input=input()

Roll_course_count[Rnum]=Roll_course_count[Rnum]+1
next_input=input()
while(next_input!="EndOfInput"):
Roll_course_count[Rnum]=Roll_course_count[Rnum]+1
next_input=input()

#print(Roll_course_count)
#print(Roll_name)

#RESULT COMPUTATION

Sort_roll=sorted(Roll_name)
for key in Sort_roll:
print(key+"~"+Roll_name[key]+"~"+str(ans))
else:
print(key+"~"+Roll_name[key]+"~"+"0")        ```

## Programming, Data Structures And Algorithms Using Python Week 4 Quiz Assignment Answers 2023

1. Consider the following Python function.

def mystery(l):
if l == []:
return(l)
else:
return(l[-1:]+mystery(l[:-1]))

What does mystery([23,35,19,58,93,46]) return?

`Answer :- [46, 93, 58, 19, 35, 23]`

2. Consider the following Python function.

def mystery(l):
if l == []:
return(l)
else:
return(l[-1:]+mystery(l[:-1]))

What does mystery([23,35,19,58,93,46]) return?

`Answer :- [(6, 2), (5, 3), (4, 2), (3, 3), (2, 2)]`

3. Consider the following dictionary.

goals = {“Country”:{“Ronaldo”:123,”Messi”:103,”Pele”:83},”Club”:{“Ronaldo”:[512,51,158],”Pele”:[604,49,26]}}

Which of the following statements does not generate an error?

goals[“Club”][“Messi”][0:] = [496,71,145]
goals[“Club”][“Messi”].extend([496,71,145])
goals[“Club”][“Messi”] = [496,71,145]
goals[“Club”][“Messi”] = goals[“Club”][“Messi”] + [496,71,145]

`Answer :- c`

4. Assume that wickets has been initialized as an empty dictionary:

wickets = {}

Which of the following generates an error?

wickets[“Muralitharan, tests”] = 800
wickets[“Muralitharan”] = {“tests”:800}
wickets[(“Muralitharan”,”tests”)] = 800
wickets[[“Muralitharan”,”tests”]] = 800

`Answer :- d`

## Programming, Data Structures And Algorithms Using Python Week 4 Programming Assignment Answers 2023

1. Write a Python function histogram(l) that takes as input a list of integers with repetitions and returns a list of pairs as follows:.

for each number n that appears in l, there should be exactly one pair (n,r) in the list returned by the function, where r is the number of repetitions of n in l.

the final list should be sorted in ascending order by r, the number of repetitions. For numbers that occur with the same number of repetitions, arrange the pairs in ascending order of the value of the number.

For instance

``````>>> histogram([13,12,11,13,14,13,7,7,13,14,12])
[(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)]

>>> histogram([7,12,11,13,7,11,13,14,12])
[(14, 1), (7, 2), (11, 2), (12, 2), (13, 2)]

>>> histogram([13,7,12,7,11,13,14,13,7,11,13,14,12,14,14,7])
[(11, 2), (12, 2), (7, 4), (13, 4), (14, 4)]``````

2. A college maintains academic information about students in three separate lists

• Course details: A list of pairs of form (coursecode,coursename), where both entries are strings. For instance,
• [ (“MA101″,”Calculus”),(“PH101″,”Mechanics”),(“HU101″,”English”) ]
• Student details: A list of pairs of form (rollnumber,name), where both entries are strings. For instance,
• [ (“UGM2018001″,”Rohit Grewal”),(“UGP2018132″,”Neha Talwar”) ]
• A list of triples of the form (rollnumber,coursecode,grade), where all entries are strings. For instance, [ (“UGM2018001”, “MA101”, “AB”), (“UGP2018132”, “PH101”, “B”), (“UGM2018001″, “PH101”, “B”) ]. You may assume that each roll number and course code in the grade list appears in the student details and course details, respectively.

Your task is to write a function transcript (coursedetails,studentdetails,grades) that takes these three lists as input and produces consolidated grades for each student. Each of the input lists may have its entries listed in arbitrary order. Each entry in the returned list should be a tuple of the form

where the student has grades for k ≥ 1 courses reported in the input list grades.

• The output list should be organized as follows.
• The tuples shold sorted in ascending order by rollnumber
• Each student’s grades should sorted in ascending order by coursecode

For instance

``````>>>transcript([("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")],[("UGM2021001","Rohit Grewal"),("UGP2021132","Neha Talwar")],[("UGM2021001","MA101","AB"),("UGP2021132","PH101","B"),("UGM2021001","PH101","B")])

[('UGM2021001', 'Rohit Grewal', [('MA101', 'Calculus', 'AB'), ('PH101', 'Mechanics', 'B')]), ('UGP2021132', 'Neha Talwar', [('PH101', 'Mechanics', 'B')])]

>>>transcript([("T1","Test 1"),("T2","Test 2"),("T3","Test 3")],[("Captain","Rohit Sharma"),("Batsman","Virat Kohli"),("No3","Cheteshwar Pujara")],[("Batsman","T1","14"),("Captain","T1","33"),("No3","T1","30"),("Batsman","T2","55") ,("Captain","T2","158"),("No3","T2","19"), ("Batsman","T3","33"),("Captain","T3","95"),("No3","T3","51")])

[('Batsman', 'Virat Kohli', [('T1', 'Test 1', '14'), ('T2', 'Test 2', '55'), ('T3', 'Test 3', '33')]), ('Captain', 'Rohit Sharma', [('T1', 'Test 1', '33'), ('T2', 'Test 2', '158'), ('T3', 'Test 3', '95')]),('No3', 'Cheteshwar Pujara', [('T1', 'Test 1', '30'), ('T2', 'Test 2', '19'), ('T3', 'Test 3', '51')])]``````

Solution Code:-

```def histogram(l):
count,ans,k = 0,list(),[]
for i in range(len(l)):
index,count=i,0
for j in range(index,len(l)):
if l[index] == l[j] and l[index] not in k :
count =count + 1
k = k + [l[index]]
if (count != 0):
ans = ans + [(l[index], count)]
ans.sort()
ans=sorted(ans,key=lambda ans:ans)
return(ans)

ans = list()
studentdetails.sort()
coursedetails.sort()
for studentdet in studentdetails:
tuple,inlist = studentdet,list()
for cdetail in coursedetails:
intuple = cdetail
inlist.append(intuple)
tuple = tuple + (inlist,)
ans.append(tuple)
return(ans)

```

## Programming, Data Structures And Algorithms Using Python Week 3 Quiz Assignment Answers 2023

1. Write a function expanding(l) that takes as input a list of integer l and returns True if the absolute difference between each adjacent pair of elements strictly increases.

Here are some examples of how your function should work.

>>> expanding([1,3,7,2,9])
True

Explanation: Differences between adjacent elements are 3-1 = 2, 7-3 = 4, 7-2 = 5, 9-2 = 7.

>>> expanding([1,3,7,2,-3]) False

Explanation: Differences between adjacent elements are 3-1 = 2, 7-3 = 4, 7-2 = 5, 2-(-3) = 5, so not strictly increasing.

>>> expanding([1,3,7,10]) False

2. Write a Python function sumsquare(l) that takes a nonempty list of integers and returns a list [odd,even], where odd is the sum of squares all the odd numbers in l and even is the sum of squares of all the even numbers in l.

Here are some examples to show how your function should work.

>>> sumsquare([1,3,5])
[35, 0]

>>> sumsquare([2,4,6])
[0, 56]

>>> sumsquare([-1,-2,3,7])
[59, 4]

3. A two dimensional matrix can be represented in Python row-wise, as a list of lists: each inner list represents one row of the matrix. For instance, the matrix

1 2 3 4
5 6 7 8

would be represented as [[1, 2, 3, 4], [5, 6, 7, 8]].

The transpose of a matrix converts each row into a column. The transpose of the matrix above is:

1 5
2 6
3 7
4 8

which would be represented as [[1, 5], [2, 6], [3, 7], [4, 8]].
Write a Python function transpose(m) that takes as input a two dimensional matrix m and returns the transpose of m. The argument m should remain undisturbed by the function.

Here are some examples to show how your function should work. You may assume that the input to the function is always a non-empty matrix.

>>> transpose([[1,2,3],[4,5,6]])
[[1, 4], [2, 5], [3, 6]]

>>> transpose([,,])
[[1, 2, 3]]

>>> transpose([])
[]

Solution:-

```def expanding(l):
if len(l) <= 2:
return(True)
diff = abs(l-l)
return(diff < abs(l-l) and expanding(l[1:]))

def expanding_loop(l):
if len(l) <= 2:
return(True)
olddiff = abs(l-l)
for i3 in range(2,len(l)):
newdiff = abs(l[i3]-l[i3-1])
if newdiff <= olddiff:
return(False)
olddiff = newdiff
return(True)

def sumsquare(l):
(odd_sum,even_sum)=(0,0)
for aa in l:
if aa%2!=0:
odd_sum+=aa*aa
else:
even_sum+=aa*aa
return([odd_sum,even_sum])

def transpose(m):
ans1=list()
for ip in range(len(m)):
a=list()
for j in range(len(m)):
a.append(m[j][ip])
ans1.append(a)
return(ans1)
```

All questions carry equal weightage. All Python code is assumed to be executed using Python3. You may submit as many times as you like within the deadline. Your final submission will be graded.Programming, Data Structures And Algorithms Using Python Week 2 Quiz Assignment Answers 2023

Note:

• If the question asks about a value of type list, remember to enclose your answer in square brackets and use commas to separate list items.

## Programming, Data Structures And Algorithms Using Python Week 2 Quiz Assignment Answers 2023

1. One of the following 10 statements generates an error. Which one? (Your answer should be a number between 1 and 10.)

``````x = ["slithy",[7,10,12],2,"tove",1]  # Statement 1
y = x[0:50]                          # Statement 2
z = y                                # Statement 3
w = x                                # Statement 4
x = x[:5] + 'ery'              # Statement 5
y = 4                             # Statement 6
z = 42                            # Statement 7
w[:3] = 'fea'                     # Statement 8
x = 5555                       # Statement 9
a = (x == 1)                   # Statement 10``````
`Answer:- 8`

2. Consider the following lines of Python code.

``````b = [23,44,87,100]
a = b[1:]
d = b[2:]
c = b
d = 97
c = 77``````

Which of the following holds at the end of this code?

• a == 77, b == 77, c == 77, d == 97
• a == 87, b == 87, c == 77, d == 97
• a == 87, b == 77, c == 77, d == 97
• a == 97, b == 77, c == 77, d == 97
`Answer:- c) a == 87, b == 77, c == 77, d == 97`

3. What is the value of endmsg after executing the following lines?

``````startmsg = "python"
endmsg = ""
for i in range(1,1+len(startmsg)):
endmsg = startmsg[-i] + endmsg``````
`Answer:- "python"`

4. What is the value of mylist after the following lines are executed?

``````def mystery(l):
l = l[1:]
return()

mylist = [7,11,13]
mystery(mylist)``````
`Answer:- [7, 11, 13]`

## Programming, Data Structures And Algorithms Using Python Week 2 Programming Assignment Answers 2023

1. A positive integer m is a prime product if it can be written as p×q, where p and q are both primes. .

Write a Python function primeproduct(m) that takes an integer m as input and returns True if m is a prime product and False otherwise. (If m is not positive, your function should return False.)

Here are some examples of how your function should work.

``````>>> primeproduct(6)
True

>>> primeproduct(188)
False

>>> primeproduct(202)
True``````

2. Write a function delchar(s,c) that takes as input strings s and c, where c has length 1 (i.e., a single character), and returns the string obtained by deleting all occurrences of c in s. If c has length other than 1, the function should return s

Here are some examples to show how your function should work.

``````>>> delchar("banana","b")
'anana'

>>> delchar("banana","a")
'bnn'

>>> delchar("banana","n")
'baaa'

>>> delchar("banana","an")
'banana'``````

3. Write a function shuffle(l1,l2) that takes as input two lists, 11 and l2, and returns a list consisting of the first element in l1, then the first element in l2, then the second element in l1, then the second element in l2, and so on. If the two lists are not of equal length, the remaining elements of the longer list are appended at the end of the shuffled output.

Here are some examples to show how your function should work.

```>>> shuffle([0,2,4],[1,3,5])
[0, 1, 2, 3, 4, 5]

>>> shuffle([0,2,4],)
[0, 1, 2, 4]

>>> shuffle(,[1,3,5])
[0, 1, 3, 5]```

``````def primeproduct(m):
P=list()
if m>=2:
for k in range(2,m):
if m%k==0:
P=P+[k]
if len(P)==2:
if m==P*P:
if P%P==0:
return(False)
return(True)
elif len(P)==1:
if m==P*P:
return(True)
else:
return(False)
else:
return(False)

def delchar(s,c):
if len(c)==1:
s=s.replace(c,'')
ans=s
else:
ans=s
return(ans)

def shuffle(l1,l2):
ans=[]
if len(l1)!=0 and len(l2)!=0:
for q in range(min(len(l1), len(l2))):
ans.extend([l1[q],l2[q]])
ans.extend(l1[q+1:] or l2[q+1:])
else:
ans.extend(l1[0:] or l2[0:])
return(ans)``````

## NPTEL Programming, Data Structures And Algorithms Using Python Week 1 Quiz Assignment Answers 2023

1. What is the value of g(728) for the function below?

``````def g(y):
b = 0
while y >= 3:
(y,b) = (y/3,b+1)
return(b)``````
`Answer :-  5`

2. What is f(90)-f(89), given the definition of f below?

```def f(n):
s = 0
for i in range(2,n):
if n%i == 0 and i%2 == 1:
s = s+1
return(s)```
`Answer :- 5`

3. Consider the following function h.

```def h(n):
s = True
for i in range(1,n+1):
if i*i == n:
s = False
return(s)
```

The function h(n) given above returns False for a positive number n if and only if:

• n is an odd number.
• n is a prime number.
• n is a perfect square.
• n is a composite number.
`Answer :- c (n is a perfect square.)`

4. Consider the following function foo.

```def foo(m):
if m == 0:
return(0)
else:
return(m+foo(m-1))
```

Which of the following is correct?

• The function always terminates with foo(n) = factorial of n
• The function always terminates with foo(n) = n(n+1)/2
• The function terminates for non­negative n with foo(n) = factorial of n
• The function terminates for non­negative n with foo(n) = n(n+1)/2
`Answer :- d  (The function terminates for non­negative n with foo(n) = n(n+1)/2)`

### 5 thoughts on “[Week 1 to 8] NPTEL Programming, Data Structures And Algorithms Using Python Assignment Answers 2023”

1. K Nandu

Programming data structure and algorithms using python week 1 assignment answers not given

2. baindla balu

Programming, Data Structures And Algorithms Using Python
3. 