[go: up one dir, main page]

0% found this document useful (0 votes)
6 views13 pages

Weekly Assignments

The document outlines weekly assignments for a programming course, detailing various Python functions to be implemented, such as checking if a number is a sum of squares, validating well-bracketed strings, rotating lists, and generating histograms. It also includes quizzes from different weeks, testing knowledge on functions and their behavior. Each assignment and quiz is accompanied by example inputs and expected outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Weekly Assignments

The document outlines weekly assignments for a programming course, detailing various Python functions to be implemented, such as checking if a number is a sum of squares, validating well-bracketed strings, rotating lists, and generating histograms. It also includes quizzes from different weeks, testing knowledge on functions and their behavior. Each assignment and quiz is accompanied by example inputs and expected outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Weekly Assignments

Week 2

1. A positive integer m is a sum of squares if it can be written as k + l where k > 0, l > 0 and both k
and l are perfect squares. Write a Python function sumofsquares(n) that takes an integer n
and returns True if n is a sum of squares and False otherwise. (If n is not positive, return False.)
For example, sumofsquares(41) → True , sumofsquares(30) → False ,
sumofsquares(17) → True .
Answer:
python
def sumofsquares(n):
if n<0:
return False
for i in range(1, int(n**0.5) + 1):
for j in range(1, int(n**0.5) + 1):
m = i**2 + j**2
if m == n:
return True
elif m > n:
break
return False 1

2. A string with parentheses is well-bracketed if all parentheses are matched: every opening
bracket has a matching closing bracket and vice versa. Write a Python function
wellbracketed(s) that takes a string s containing parentheses and returns True if s is well-
bracketed and False otherwise. Hint: Track the nesting depth. For example,
wellbracketed("22)") → False , wellbracketed("(a+b)(a-b)") → True ,
wellbracketed("(a(b+c)-d)((e+f)") → False .
Answer:
python
def wellbracketed(ss):
depth = 0
for char in ss:
if char == "(":
depth += 1
elif char == ")":
if depth > 0:
depth -= 1
else:
return False
return depth == 0 2

3. A list rotation consists of taking the last element and moving it to the front. For example,
rotating [1,2,3,4,5] once yields [5,1,2,3,4], and rotating again yields [4,5,1,2,3]. Write a Python
function rotatelist(l, k) that takes a list l and a positive integer k and returns the list l
after k rotations. If k is not positive, return l unchanged. The function should not modify l in

1
place. For example, rotatelist([1,2,3,4,5],1) → [5,1,2,3,4] ,
rotatelist([1,2,3,4,5],3) → [3,4,5,1,2] , rotatelist([1,2,3,4,5],12) →
[4,5,1,2,3] .
Answer:
python
def rotatelist(ll, shft):
l = len(ll)
shft = shft % l
ans = ll[l-shft:] + ll[:l-shft]
return ans 3

Week 3

1. Define a Python function ascending(l) that returns True if each element in its input list is at
least as big as the one before it. For example, ascending([]) → True ,
ascending([3,3,4]) → True , ascending([7,18,17,19]) → False .
Answer:
python
def ascending(lst):
for i in range(0, len(lst) - 1):
if lst[i] > lst[i+1]:
return False
return True 4

2. A list of integers is said to be a valley if it consists of a strictly decreasing sequence followed by a


strictly increasing sequence. The decreasing and increasing sequences must be of length at least
2, and the last value of the decreasing sequence is the first of the increasing sequence. Write a
Python function valley(l) that returns True if l is a valley and False otherwise. For example,
valley([3,2,1,2,3]) → True , valley([3,2,1]) → False ,
valley([3,3,2,1,2]) → False .
Answer:
python
def valley(lst):
flag = False
for i in range(0, len(lst) - 1):
if lst[i] == lst[i+1]:
return False
if not flag:
if lst[i] > lst[i+1]:
continue
if lst[i] < lst[i+1]:
flag = True
else:
if lst[i] > lst[i+1]:
return False
elif lst[i] < lst[i+1]:
continue
return flag 5

2
3. A two-dimensional matrix can be represented as a list of lists (each inner list is a row). Write a
Python function transpose(m) that takes such a matrix m and returns its transpose (also as a
list of lists). For example, transpose([[1,4,9]]) → [[1],[4],[9]] ;
transpose([[1,3,5],[2,4,6]]) → [[1,2],[3,4],[5,6]] ; transpose([[1,1,1],
[2,2,2],[3,3,3]]) → [[1,2,3],[1,2,3],[1,2,3]] . Assume m is non-empty.
Answer:
python
def transpose(lst):
return [list(x) for x in zip(*lst)] 6

Week 4

1. Write a Python function histogram(l) that takes a list of integers (with repetitions) and
returns a list of pairs (n, r) where r is the count of n in l. The output list should be sorted in
ascending order by count (r); for equal counts, sort by the integer value. For example,
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)] .
Answer:
python
def histogram(l):
d = {}
for i in l:
d[i] = d.get(i, 0) + 1
ans = [(a, d[a]) for a in d]
ans = sorted(ans, key=lambda x: (x[1], x[0]))
return ans 7

2. A college has: Course details as a list of (coursecode, coursename), Student details as


(rollnumber, name), and Grades as (rollnumber, coursecode, grade). Write a function
transcript(coursedetails, studentdetails, grades) that produces a consolidated
list for each student: (rollnumber, name,
[(coursecode_1,coursename_1,grade_1),…]) . The output list should be sorted by
rollnumber, and each student’s courses sorted by coursecode.
Answer:
python
def transcript(coursedetails, studentdetails, grades):
list_out = []
studentdetails.sort()
coursedetails.sort()
grades.sort()
for studentdet in studentdetails:
roll, name = studentdet
courses = []
for grade in grades:
if studentdet[0] == grade[0]:
for cdetail in coursedetails:
if grade[1] == cdetail[0]:
intuple = cdetail + (grade[2],)

3
courses.append(intuple)
list_out.append((roll, name, courses))
return list_out 8

Weekly Quizzes

Week 1 (July 2017)

1. What would happen if we call gcd(m,n) with m positive and n negative in the following
definition?

def gcd(m,n):
if m < n:
(m,n) = (n,m)
if (m % n) == 0:
return n
else:
diff = m-n
return gcd(max(n,diff),min(n,diff))

Options: (a) The behavior depends on the values of m and n. (b) The function still computes gcd
correctly. (c) The function does not terminate. Answer: (a). 9

2. What can we say about an integer n if h(n) returns True for the function below?

def h(n):
for i in range(2,n):
if n % i == 0:
return True
return False

Options: (a) n is a multiple of 2. (b) n is composite. (c) n is prime. (d) n has at least two distinct
factors other than 1 and n.
Answer: (b) n is a composite number. 10

3. What does f(120,13) return for the following function?

def f(m,n):
ans = 1
while (m - n >= 0):
(ans,m) = (ans*2, m-n)
return ans

Answer: 512. 11

4. What is the value of list1 after executing the following code?

4
def mystery(l):
l = l[2:5]
return
list1 = [7,82,44,23,11]
mystery(list1)

Answer: [7,82,44,23,11] (the list is unchanged). 12

Week 1 (Jan 2018)

1. What does f(31415927) return for:

def f(x):
d = 0
while x > 1:
(x,d) = (x/2, d+1)
return d

Answer: 25 13

2. What is the value of h(6,8) for:

def h(m,n):
ans = 1
while n > 0:
(ans,n) = (ans*m, n-2)
return ans

Answer: 1296 14

3. The function h(n) below returns True for positive n when:

def h(n):
f = 0
for i in range(1,n+1):
if n % i == 0:
f = f + 1
return (f == 2)

(A) n is a multiple of 2; (B) n is composite; (C) n is prime; (D) n has an even number of factors.
Answer: (C) n is a prime number 15

4. Consider:

5
def f(m):
if m == 0:
return 1
else:
return m * f(m-1)

(A) Always terminates with f(n)=n.


(B) Always terminates with f(n)=factorial of n.
(C) Terminates for non-negative n with f(n)=n.
(D) Terminates for non-negative n with f(n)=factorial of n.
Answer: (D) Terminates for non-negative n with f(n) = factorial of n 16

Week 2 (July 2017)

1. One of the following 10 statements generates an error. Which one?

x = [1,"abcd",2,"efgh",[3,4]] # 1
y = x[0:50] # 2
z = y # 3
w = x # 4
x[1] = x[1][0:3] + 'd' # 5
y[2] = 4 # 6
z[0] = 0 # 7
x[1][1:2] = 'yzw' # 8
w[4][0] = 1000 # 9
a = (x[4][1] == 4) # 10

Answer: Statement 8 causes an error. 17

2. After executing:

x = ['a', 42, 'b', 377]


w = x[1:]
y = x
u = w
w = w[0:]
w[0] = 53
x[1] = 47

Which of the following is correct?

3. (a) x[1]==47, y[1]==47, w[0]==53, u[0]==42


4. (b) x[1]==47, y[1]==42, w[0]==53, u[0]==42
5. (c) x[1]==47, y[1]==47, w[0]==53, u[0]==53

6. (d) x[1]==47, y[1]==42, w[0]==53, u[0]==53


Answer: (a) x[1]==47, y[1]==47, w[0]==53, u[0]==42 18

6
7. What is the value of second after:

first = "wombat"
second = ""
for i in range(len(first),0,-1):
second = first[i-1] + second

Answer: "wombat" 19

8. What is the value of list1 after:

def mystery(l):
l = l[2:5]
return
list1 = [7,82,44,23,11]
mystery(list1)

Answer: [7,82,44,23,11] (unchanged) 12

Week 2 (Jan 2018)

1. One of the following 10 statements generates an error. Which one?

x = [[7,8],3,"hello",[6,8],"world",17] # 1
z = [x[0],x[3]] # 2
y = x[0:50] # 3
w = x # 4
w[0][1] = 7 # 5
a = z[0][1] + z[1][1] # 6
x[0] = "ping" # 7
y[2] = y[2][1] + y[4][2] # 8
y[0][1] = 7 # 9
w[0][1] = 7 # 10

Answer: Line 10 causes an error. 20

2. What is the value of mystring after:

def mystery(s):
for i in range(len(s), 1, -2):
s = s[1:] + s[0]
return s

mystring = "siruseri"
mystring = mystery(mystring)

7
Answer: "serisiru" 21

3. Consider:

a = 'nptel'
b = [12,14,16]
c = 72

x = [a,b,c]
y = [a,b[:],c]
u = x[:]
v = y

b[1] = 17
v[1][1] = 15

Which is correct?

4. (a) x[1][1]==14, y[1][1]==14, u[1][1]==15, v[1][1]==15


5. (b) x[1][1]==17, y[1][1]==15, u[1][1]==14, v[1][1]==15
6. (c) x[1][1]==17, y[1][1]==15, u[1][1]==17, v[1][1]==15

7. (d) x[1][1]==14, y[1][1]==15, u[1][1]==14, v[1][1]==15


Answer: (c) x[1][1]==17, y[1][1]==15, u[1][1]==17, v[1][1]==15 22

8. Now:

a = 'nptel'
b = [12,14,16]
c = 72

x = [a,b,c]
y = [a,b[:],c]
u = x[:]
v = y

b = [12,17,16]
v[1][1] = 15

Which is correct?

9. (a) x[1][1]==14, y[1][1]==14, u[1][1]==15, v[1][1]==15


10. (b) x[1][1]==17, y[1][1]==15, u[1][1]==14, v[1][1]==15
11. (c) x[1][1]==17, y[1][1]==15, u[1][1]==17, v[1][1]==15
12. (d) x[1][1]==14, y[1][1]==15, u[1][1]==14, v[1][1]==15
Answer: (d) x[1][1]==14, y[1][1]==15, u[1][1]==14, v[1][1]==15 23

8
Week 4 (Jan 2018)

1. Consider the function:

def mystery(l):
if len(l) < 2:
return l
else:
return mystery(l[1:]) + [l[0]]

What does mystery([17,12,41,28,25]) return?


Answer: [25, 28, 41, 12, 17] 24

2. What is the value of triples after:

triples = [(x,y,z)
for x in range(1,4)
for y in range(x,4)
for z in range(y,4)
if x+y <= z]

Answer: [(1, 1, 2), (1, 1, 3), (1, 2, 3)] 25

3. Given a dictionary marks , which statement changes Suresh’s exam marks to [44]?
(a) marks["Exams"]["Suresh"].extend([44])
(b) marks["Exams"]["Suresh"].append(44)
(c) marks["Exams"]["Suresh"] = [44]
(d) marks["Exams"]["Suresh"][0:] = [44]
Answer: (c) marks["Exams"]["Suresh"] = [44] 26

4. Assume grandslams = {} . Which is valid? (a)


grandslams[("Federer","Wimbledon")] = 8
(b) grandslams[["Federer","Wimbledon"]] = 8
(c) grandslams["Federer, Wimbledon"] = 8
(d) grandslams["Federer"] = ["Wimbledon",8]
Answer: (b) grandslams[["Federer","Wimbledon"]] = 8 (this raises a TypeError because
lists are unhashable) 27

Final Exam Questions

2017 (July)

1. Here is a function to return the maximum value in a list of integers, but it has an error. Give an
input list for which maxbad(l) produces an incorrect output.

def maxbad(l):
end = len(l) - 1

9
mymax = l[-1]
for i in range(end,0,-1):
if l[i] > mymax:
mymax = l[i]
return mymax

Answer: For example, [-3, -2, -1] (this yields incorrect result). 28

2. Here is a version of quicksort with a bug. Provide an input list for which quicksortbad(l)
gives an incorrect result.

def quicksortbad(l):
if len(l) < 2:
return l
else:
pivot = l[0]
smaller = [l[j] for j in range(1,len(l)) if l[j] < pivot]
bigger = [l[j] for j in range(1,len(l)) if l[j] > pivot]
rearrange = quicksortbad(smaller) + [pivot] +
quicksortbad(bigger)
return rearrange

Answer: For example, [5,5,5,5,5] or [1,2,2,3] . 29

3. Fill in the missing lines to compute the smallest of three integers.

def min3(x,y,z):
if x <= y:
if x <= z:
minimum = x
# Your code below this line

# Your code above this line


return minimum

Answer:
python
elif y <= z:
minimum = y
else:
minimum = z 30

4. Fill in the missing argument for this recursive list-reversal function:

def myreverse(l):
if l == []:
return l

10
else:
return (....)

Answer: myreverse(l[1:]) + [l[0]] 31

5. A positive integer n is square-free if it is not divisible by any square >1. For example, 5, 10, 21 are
square-free; 4 and 48 are not. Write a Python function squarefree(n) that returns True if n is
square-free, False otherwise.
Answer:
python
def squarefree(n):
for i in range(2, n):
if n % (i*i) == 0:
return False
return True 32

6. Write a Python function disjointlist(l1,l2) that takes two lists and returns True if they
are disjoint (no element in common), else False. For example, disjointlist([2,2,3,4,5],
[6,8,8,1]) → True , disjointlist([1,2,3,4],[2,2]) → False .
Answer:
python
def disjointlist(l1, l2):
for x in l1:
if x in l2:
return False
return True 33

7. Read an even number of lines of text from input, terminated by a blank line. Suppose there are
2n lines; your program should print the last n lines (second half) followed by the first n lines (first
half). For example, input:

our dear friend,


let’s eat

should produce:

let’s eat
our dear friend,

Answer:
python
lines = []
line = input().rstrip('\n')
while line != '':
lines.append(line)
line = input().rstrip('\n')
n = len(lines)
for i in range(n//2, n):

11
print(lines[i])
for i in range(0, n//2):
print(lines[i]) 34 35

8. Write a Python function maxcount(l) that returns the number of times the most frequent
value occurs in list l. For example, maxcount([1,17,31,17,22,17]) → 3 (17 appears 3
times),
maxcount(["the","higher","you","climb","the","further","you","fall"]) → 2 .
Answer:
python
def maxcount(l):
mcount = 0
for i in l:
count = 0
for j in l:
if i == j:
count += 1
if count > mcount:
mcount = count
return mcount 36

Sources: All questions and answers are from publicly available NPTEL course resources 4 28 (see
links for individual questions).

12
1 2 3 Week 2 Programming Assignment | NPTEL Programming, Data Structures and Algorithms

using Python | Apr 2018 | Hackademic


https://hackademic.co.in/solution-for-nptel-programming-data-structures-and-algorithms-using-python-week-2-
programming-assignment-2-apr-2018/

4 5 Solution for NPTEL Programming, Data Structures and Algorithms using Python, Week 3
6

Programming Assignment | Hackademic


https://hackademic.co.in/solution-for-nptel-programming-data-structures-and-algorithms-using-python-week-3-
programming-assignment/

7 8 Week 4 | Programming Assignment Updated | Programming, Data Structures and Algorithms


using Python | Apr 2018 | Hackademic
https://hackademic.co.in/week-4-program-python-apr-2018/

9 10 Solution for NPTEL Programming, Data Structures and Algorithms using Python Week 1
11

MCQs | Hackademic
https://hackademic.co.in/solution-for-nptel-programming-data-structures-and-algorithms-using-python-week-1-mcqs/

12 17 18Solution for NPTEL Programming, Data Structures and Algorithms using Python Week 2
19

MCQs | Hackademic
https://hackademic.co.in/solution-for-nptel-programming-data-structures-and-algorithms-using-python-week-2-mcqs/

13 14 15 16 Week 1 Quiz | Programming, Data Structures And Algorithms Using Python | Apr 2018 |
Hackademic
https://hackademic.co.in/week-1-quiz-python-apr-2018/

20 21 22 23 Week 2 Quiz | Programming, Data Structures And Algorithms Using Python | Apr 2018 |
Hackademic
https://hackademic.co.in/week-2-quiz-programming-data-structures-and-algorithms-using-python-apr-2018/

24 25 26 27 Week 4 Quiz Answers | Programming, Data Structures And Algorithms Using Python |

Apr 2018 | Hackademic


https://hackademic.co.in/week-4-quiz-python-apr-2018/

28 29 30 31 32 33 ONLINE TEST 9-12 AM | Solution for NPTEL Programming, Data


34 35 36

Structures and Algorithms using Python | Hackademic


https://hackademic.co.in/online-test-9-12-am-solution-for-nptel-programming-data-structures-and-algorithms-using-python/

13

You might also like