**NPTEL Programming Data Structures And Algorithms Using Python **This course is an introduction to programming and problem-solving in Python. This course helps students to understand the concepts of data structures and algorithms using python, without having any prior knowledge of programming concepts.

**Programming Data Structures And Algorithms Using Python** is a MOOC course offered by IIT Kharagpur on the NPTEL platform. This course helps the students to achieve problem-solving methods through a programming language. The course is developed by **Prof. Madhavan Mukund studied at IIT Bombay (BTech) and Aarhus University (PhD). **

**Who Can Join:**All UG/PG students.**Requirements/Prerequisites:**Nil.**INDUSTRY SUPPORT:**All IT Industries

**CRITERIA TO GET A CERTIFICATE**

Average assignment score = 25% of the average of the best 6 assignments out of the total 8 assignments given in the course.

Exam score = 75% of the proctored certification exam score out of 100 Final scores = Average assignment score + Exam score

Students will be eligible for CERTIFICATE ONLY IF AVERAGE ASSIGNMENT SCORE >=10/25 AND EXAM SCORE >= 30/75. If any of the 2 criteria are not met, the student will not get the certificate even if the Final score >= 40/100.

## Programming Data Structures And Algorithms Using Python online programming test Evening:-

Contents

- 1 Programming Data Structures And Algorithms Using Python online programming test Evening:-
- 2 Programming Data Structures And Algorithms Using Python online programming test:-
- 3 Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 5 ANSWERS:-
- 4 Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 4 ANSWERS:-
- 5 Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 3 ANSWERS:-
- 6 Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 2 ANSWERS:-

**Q1.** Here is an function to return the maximum value in a list of integers. There is an error in this function. Provide an input list for which maxbad produces an incorrect output.

**Code:-**

```
[-1,-9,-6,-6]
```

**Q2.** Here is a function to check if there are any repeated values among four input integers. You have to fill in the missing lines.

**Code:-**

```
if a!=c:
if a!=d:
if b!=d:
if c!=d:
return False
return True
```

**Q3.** A list is increasing if each element is strictly larger than the preceding one. For instance [], [7], [8,11] and [3,19,44,63,89] are increasing, while [4,18,3] and [3,14,14,23] are not. Here is a recursive function to check if a list is increasing. You have to fill in the missing argument for the recursive call.

**Code:-**

```
l[0]<l[1] and increasing(l[1:])
```

**Q4.** A positive integer *n* is a sum of cubes if *n = i ^{3} + j^{3}* for integers

*i,j*such that

*i ≥ 1*and

*j ≥ 1*. For instance, 9 is a sum of cubes because 9 = 1

^{3}+ 2

^{3}, and so is 35 (2

^{3}+ 3

^{3}). On the other hand, 25 and 49 are not sums of cubes.

**Code:-**

```
def sumofcubes(n):
for i in range(1,n):
add = i**3 + (i+1)**3
if add == n:
return True
break
else:
return False
```

**Q5.** Given two lists of integers, l1 and l2, we want to identify those integers from each of the lists that are also present in the other list. For instance if l1 is [1,2,4,9,1,2] and l2 is [2,3,4,5,4,7,7], we identify [2,4,2] as the numbers from the first list that are present in the second list and [2,4,4] as the numbers from the second list that are present in the first list.

**Code:-**

```
def dif(l1, l2):
li_diff = [i for i in l1 if i in l2]
return(li_diff)
def listcommon(l1,l2):
return (dif(l1,l2),dif(l2,l1))
```

**Q6.** Define a Python function listdup(l) that takes a nonempty list of integers l and returns one copy of each number that appears with repetitions in l. These should be listed in the same order as their first appearance in l. For instance:

**Code:-**

```
def listdup(l):
con = {}
tup = list()
for i in l:
if i not in con:
con[i] = 1
else:
con[i] = con.get(i, 0) + 1
for (key, value) in con.items():
if value > 1:
tup.append(key)
return tup
```

**Q7.** Write a Python program that reads input from the keyboard (standard input). The input will consist of some number of lines of text. The input will be terminated by a blank line. The first line will consist of a single word. Your program should count the number of times the letters in this word appear in the remaining text, from the second line onwards. For instance, if the first line contains the word banana, you should count the number of occurrences of letters from the set {‘b’,’a’,’n’}. This count is cumululative, so you should add the number of times ‘b’, ‘a’ and ‘n’ occur and report your answer. Letters are case-sensitive, so ‘b’ and ‘B’ are different, for instance.

**Code:-**

```
word = input()
s = set(word)
count = 0
while True:
line = input()
if line == "":
break
for i in line:
if i in s:
count += 1
print(count)
```

**Q8.** The marks scored by each student in Physics and Mathematics is recorded as a triple as follows: (StudentName,PhysicsMarks,MathematicsMarks). For instance, the triple (‘Balaji’,72,94) records that the student named Balaji scored 72 in Physics and 94 in Mathematics.

**Code:-**

```
def studypairs(l):
(phys, maths) = (0,0)
pairs = []
for i in l:
for j in l:
if i!=j:
# conditioning the statements
if (i[2]>j[2]) and (i[1]<j[1]) and (abs(i[1]-j[1])>=10) and (abs(i[2]-j[2])>=10):
new_tuple = (i[0], j[0])
pairs.append(tuple(sorted(new_tuple)))
return (sorted(pairs))
```

## Programming Data Structures And Algorithms Using Python online programming test:-

**Q1.** Here is a function isprimebad that takes a positive integer as input and returns True if the number is prime and False otherwise. There is an error in this function. Provide an input n, which is a positive integer, for which isprimebad produces an incorrect output.

**Code:-**

`25`

** Q2.** Here is a function to check if three input integers are all different from each other. You have to fill in the missing lines.

**Code:-**

```
if (a!=c):
return True
return False
```

**Q3.** Recall that the positions in a list of length n are 0,1,…,n-1. We want to write a function evenpositions(l) that returns the elements at the even positions in l. In other words, the function should return the list [l[0],l[2],…]. For instance evenpositions([]) == [], evenpositions([7]) == [7], evenpositions([8,11,8]) == [8,8] and evenpositions([19,3,44,44,3,19]) == [19,44,3]. A recursive definition of evenpositions is given below. You have to fill in the missing argument for the recursive call.

**Code:-**

```
[l[0]]+evenpositions(l[2:])
```

**Q4.** A positive integer is said to be cube free, if it is not divisible by any cubic integer strictly greater than 1. For instance, 5, 10 and 21 are cube free, while 24 and 108 are not, since 24 is divisible by 2^{3} and 108 is divisible by 3^{3}.

**Code:-**

```
def cubefree(n):
s=[]
i=2
while (i*i*i)<n:
s.append(i*i*i)
i+=1
for i in s:
if n%i==0:
return False
return True
```

**Q5.** Given two lists of integers, l1 and l2, we want to identify the integers from each of the lists that are not present in the other list. For instance if l1 is [1,2,4,9,1,2] and l2 is [2,3,4,5,4,7,7], we identify [1,9,1] as the numbers from the first list that are not in the second list and [3,5,7,7] as the numbers from the second list that are not in the first list.

**Code:-**

```
def dif(li1, li2):
li_dif = [i for i in li1 if i not in li2]
return li_dif
def listdiff(l1,l2):
return (dif(l1,l2),dif(l2,l1))
```

**Q6.** Write a Python program that reads input from the keyboard (standard input). The input will consist of some number of lines of text. The input will be terminated by a blank line. The first line will consist of a single word to be interpreted as a *forbidden pattern*, after discarding the new line character. Your program should print every line from the second line onward that *does not contain* an occurrence of the forbidden pattern. You can assume that the input will have a non-empty pattern line.

**Code:-**

```
def deldup(l):
lcopy=[]
for e in l:
if count(l,e)==1:
lcopy.append(e)
return lcopy
def count(l,x):
cnt=0
for e in l:
if x==e:
cnt+=1
return cnt
```

**Q7.** Write a Python program that reads input from the keyboard (standard input). The input will consist of some number of lines of text. The input will be terminated by a blank line. The first line will consist of a single word to be interpreted as a *forbidden pattern*, after discarding the new line character. Your program should print every line from the second line onward that *does not contain* an occurrence of the forbidden pattern. You can assume that the input will have a non-empty pattern line.

**Code:-**

```
forbidden = input()
while True:
try :
line = input()
if line == "":
break
if forbidden not in line:
print(line)
except EOFError:
break
```

**Q8.** The marks scored by each student in Physics, Chemistry and Mathematics is recorded as 4-tuple as follows: (StudentName,PhysicsMarks,ChemistryMarks,MathematicsMarks). For instance, the tuple (‘Balaji’,85,72,94) records that the student named Balaji scored 85 in Physics, 72 in Chemistry and 94 in Mathematics.

The marks for the entire class is stored as a list of such tuples. For instance, [(‘Clare’,92,84,88),(‘Balaji’,85,72,94),(‘Mousum’,75,94,68)].

**Code:-**

```
def aboveaverage(l):
p=0;
c=0;
m=0;
result=[]
for e in l:
p +=e[1]
c += e[2]
m += e[3]
for e in l:
count=0
if e[1]>=p/len(l):
count+=1
if e[2] >= c / len(l):
count += 1
if e[3] >= m / len(l):
count += 1
if count>=2:
result.append(e[0])
return result
```

## Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 5 ANSWERS:-

**Q1.** The library at the Hogwarts School of Witchcraft and Wizardry has computerized its book issuing process. The relevant information is provided as text from standard input in three parts: information about books, information about borrowers and information about checkouts. Each part has a specific line format, described below.

**Code:-**

**FOR QUIZ ASSIGNMENT ANSWERS :- PROGRAMING DS AND ALGO QUIZ ASSIGNMENT**

```
books = dict()
# Dictionary to map username to fullname
borrowers = dict()
# List to store checkout data: accumulate, sort and print
checkouts = []
# Find the start of Books data
nextline = input().strip()
while nextline.find("Books") < 0:
nextline = input().strip()
# Read upto start of Borrowers data
# Skip the line with "Books"
nextline = input().strip()
while nextline.find("Borrowers") < 0:
(accession_number,title) = nextline.split('~')
books[accession_number] = title
nextline = input().strip()
# Read upto Checkout data
# Skip the line with "Borrowers"
nextline = input().strip()
while nextline.find("Checkouts") < 0:
(username,fullname) = nextline.split('~')
borrowers[username] = fullname
nextline = input().strip()
# Process Checkouts
# Skip the line with "Checkouts"
nextline = input().strip()
while nextline.find("EndOfInput") < 0:
(username,accession_number,due_date) = nextline.split('~')
checkoutline = due_date+"~"+borrowers[username]+"~"+accession_number+"~"+books[accession_number]
checkouts.append(checkoutline)
nextline = input().strip()
# Print the output from checkouts
for i in sorted(checkouts):
print(i)
```

## Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 4 ANSWERS:-

**Q1.** Write two Python functions as specified below. Paste the text for both functions together into the submission window. Your function will be called automatically with various inputs and should return values as specified. Do not write commands to read any input or print any output.

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

A college maintains academic information about students in three separate lists

**Code:-**

**FOR QUIZ ASSIGNMENT ANSWERS :- PROGRAMING DS AND ALGO QUIZ ASSIGNMENT**

```
def histogram(l):
count = 0
ans=list()
k=list()
for i in range(len(l)):
index=i
count=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[1])
return ans
def transcript(coursedetails, studentdetails, grades):
ans = list()
studentdetails.sort()
coursedetails.sort()
grades.sort()
for studentdet in studentdetails:
tuple = studentdet
inlist = []
for grade in grades:
if studentdet[0] == grade[0]:
for cdetail in coursedetails:
if grade[1] == cdetail[0]:
intuple = cdetail
intuple = intuple + (grade[2],)
inlist.append(intuple)
tuple = tuple + (inlist,)
ans.append(tuple)
return ans
```

## Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 3 ANSWERS:-

**Q1. **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.

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

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

**Code:-**

**FOR QUIZ ASSIGNMENT ANSWERS :- PROGRAMING DS AND ALGO QUIZ ASSIGNMENT**

```
def expanding(l):
L=list()
a=0
b=0
d=0
for i in range(0,len(l)-1,1):
a=i
b=i+1
if(l[a]>l[b]):
d=l[a]-l[b]
else:
d=l[b]-l[a]
L.append(d)
A=0
B=0
c=0
for i in range(0,len(L)-1,1):
A=i
B=i+1
if(L[A]>=L[B]):
c=c+1
return(c==0)
def sumsquare(l):
odd=0
even=0
for a in l:
if a%2==0:
even = even + a**2
else:
odd = odd + a**2
l=[odd,even]
return(l)
def transpose(m):
rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
ans=[]
for row in rez:
ans.append(row)
return(ans)
```

## Programming Data Structures And Algorithms Using Python ASSIGNMENT WEEK 2 ANSWERS:-

**Q1.** 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.)

**Code:-**

```
def f(n):
flist = []
for i in range(1,n+1):
if n%i == 0:
flist.append(i)
return(flist)
def check_prime(n):
return(f(n) == [1,n])
def primeproduct(n):
for i in range(1,n+1):
if n%i == 0:
if check_prime(i) and check_prime(n//i):
return(True)
return(False)
def delchar(s,c):
if len(c)==1:
return(s.replace(c,''))
else:
return(s)
def shuffle(l1,l2):
t=max(len(l1),len(l2))
ans=list()
for i in range(t):
try:
ans.append(l1[i])
except:
pass
try:
ans.append(l2[i])
except:
pass
return(ans)
```

**Also Check:- INTERNSHIP OPPORTUNITIES**