0% found this document useful (0 votes)
3K views205 pages

CT Ga

Uploaded by

sinhatushar.iitm
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)
3K views205 pages

CT Ga

Uploaded by

sinhatushar.iitm
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/ 205

Graded assignment week 1

Graded assignment week 1


Question (1 to 3)
Statement
Question 1 [2 Marks]
Statement
Answer
Question 2 [2 Marks]
Statement
Answer
Question 3 [2 Marks]
Statement
Answer
Solution
Question 4 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 5 [5 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 6 [5 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 7 [5 Marks]
Statement
Options
(a)
(b)
(c)
(f)
Answer
Solution
Question 8 [5 Marks]
Statement
Options
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
Answer
Solution
Question 9 [5 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 10 [5 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution

Question (1 to 3)
Statement
What will be the values of A, B and C after execution of the following procedure using the
"Shopping Bills" dataset?

Step 1: Arrange all cards in a single pile called Pile 1

Step 2: Initialize variables A, B, and C to 0

Step 3: If Pile 1 is empty then stop the iteration

Step 4: Read the top card in Pile 1

Step 5: If total bill amount >= 500 then increment A

Step 6: If total bill amount < 500 and total bill amount >= 100 then increment B

Step 7: If total bill amount < 100 then increment C

Step 8: Move the current card to another pile called Pile 2 and repeat from step 3

Question 1 [2 Marks]
Statement
The value of A is _ _ _ _ ?

Answer
16

Question 2 [2 Marks]
Statement
The value of B is _ _ _ _ ?

Answer
12

Question 3 [2 Marks]
Statement
The value of C is _ _ _ _ ?

Answer
2

Solution
In this question we have to find exact values of three variables A, B and C. So, let us start with the
procedure. Here in step 2 we have declared three variables A, B, C and also initialized them to 0.
Step 3 checks whether the iteration has to be continued or not. If the pile 1 is empty then the
iteration has to be stopped. In Step 4, the top card of the Pile 1 is taken and read. In step 5,
variable A is getting incremented if total bill amount is greater than or equal to 500. In this step 6
variable B is getting incremented if total bill amount lies between 500 and 100, 500 is not included
and 100 is included. C is incremented if the total bill amount is less than 100. Finally, in Step 8, the
current card is moved to another called Pile 2 and the procedure is repeated from Step 3.

Cards counted under variable Card numbers

A 1, 2, 3, 5, 8, 9, 11, 13, 14, 18, 19, 20, 23, 25, 28, 30

B 4, 6, 10, 12, 15, 16, 17, 21, 22, 26, 27, 29

C 7, 24
Question 4 [4 Marks]
Statement
The following pseudocode is executed using the "Words" dataset. What will count represent at
the end of the execution?

Step 1: Arrange all cards in a single pile called Pile 1

Step 2: Initialize variable count to 0

Step 3: If Pile 1 is empty then stop the iteration

Step 4: Read the top card in Pile 1

Step 5: If the Word ends with full stop and the Word is "Monday" then increment count

Step 6: Move the current card to another pile called Pile 2 and repeat from step 3

Options
(a)

Frequency count of the word Monday in the dataset

(b)

Number of sentences which start with the word Monday

(c)

Number of sentences consisting the word Monday at least once

(d)

Number of sentences which ends with the word Monday

Answer
(d)

Solution
Let us analyze the given procedure, in step 2 two variables A and count are initialized to 0.

In step 5 count is being incremented if the last word of a sentence is "Monday"

Finally, in Step 6, the current card is moved to another called Pile 2 and the procedure is repeated
from Step 3. Hence, count represents the number of sentences which ends with the word
Monday
Question 5 [5 Marks]
Statement
A student proposed a hypothesis that more people are born in the first half of the year than the
second half of the year. She wrote the following procedure which uses the “Scores” dataset to
verify the hypothesis.

Step 1: Arrange all cards in a single pile called Pile 1

Step 2: Maintain two variables A and B and initialize them to 0

Step 3: If Pile 1 is empty then stop the iteration and start from step 8

Step 4: Read the top card in Pile 1

Step 5: ---------------------------------------------------------------------------------------

Step 6: ---------------------------------------------------------------------------------------

Step 7: Move the current card to another pile called Pile 2 and repeat from step 3

Step 8: ---------------------------------------------------------------------------------------

Step 9: ---------------------------------------------------------------------------------------

Fill in the missing steps.

Options
(a)

Step 5: If A ≤ B then declare the hypothesis to be False

Step 6: If A is same as B then declare the hypothesis to be True

Step 8: If the Date of Birth is from 1st March to 30th June then increment A

Step 9: If the Date of Birth is from 1st July to 28th February then increment B

(b)

Step 5: If A ≤ B then declare the hypothesis to be False

Step 6: If A > B then declare the hypothesis to be True

Step 8: If the Date of Birth is from 1st January to 31th July then increment A

Step 9: If the Date of Birth is from 1st August to 31st December then increment B

(c)

Step 5: If the Date of Birth is from 1st January to 30th June then increment A

Step 6: If the Date of Birth is from 1st July to 31st December then increment B

Step 8: If A > B then declare the hypothesis to be True

Step 9: If A ≤ B then declare the hypothesis to be False


(d)

Step 5: If the Date of Birth is from 1st January to 30th June then increment A

Step 6: If the Date of Birth is from 1st July to 31st December then increment B

Step 8: If A ≤ B then declare the hypothesis to be True

Step 9: If A > B then declare the hypothesis to be False

Answer
(c)

Solution
In Step 1 cards are arranged into a single pile and which is called as Pile 1. In Step 2 we are
creating two variables called A and B then assigning the value 0 to them. Step 3 checks whether
the iteration has to be continued or not. If the pile 1 is empty then the iteration has to be stopped.
In Step 4, the top card of the Pile 1 is taken and read. Now, one has to count the number of
people who are born in the first half of the year and who are born in the second half of the year.
From the given options, third and fourth are seemed to be valid steps for 5 and 6. In Step 7, the
current card is moved to another called Pile 2 and the procedures are repeated from Step 3. After
reading all cards, variables A and B will store the number of students whose Date Of Birth are in
the first and the second half of the year respectively. So to verify the hypothesis, the values of A
and B should be compared with each other. If the value of A is greater than B it will confirm the
hypothesis to be True and if the value of A is lesser than or equal to B it will confirm the
hypothesis to be False. From the third and fourth options, the correct steps for 8 and 9 are found
in the third option. Hence, third option is correct.

Question 6 [5 Marks]
Statement
What will the given procedure compute and store in variable X if executed on the "Shopping Bills"
dataset?

Step 1: Arrange all cards in a single pile called Pile 1


Step 2: Maintain four variables A, B, C, X and initialize them to 0
Step 3: If Pile 1 is empty then stop the iteration and start from step 9
Step 4: Read the top card in Pile 1
Step 5: If the Shop name is "SV Stores" and Customer name is "Neeraja" then set A equal to 1
Step 6: If the Shop name is "Big Bazaar" and Customer name is "Neeraja" then set B equal to 1
Step 7: If the Shop name is "Sun General" and Customer name is "Neeraja" then set C equal to 1
Step 8: Move the current card to another pile called Pile 2 and repeat from step 3
Step 9: Update the value of X as X = A + B + C
Options
(a)

Numbers of bills in the dataset which belong to Neeraja

(b)

Numbers of times Neeraja has visited Sun General

(c)

Number of distinct stores which Neeraja never visited

(d)

Number of distinct stores which Neeraja has visited

Answer
(d)

Solution
Variables A, B, C, and X are initialized to 0 in step 2. In step 5 variable A's value will be set to 1 if
"Neeraja" has a shopping bill from "SV stores". Similarly, in step 6 variable B's value will be set to 1
if she has a bill from "Big Bazaar" and variable C's value for "Sun General" in step 7.
In step 9 value of X is updated to with sum of A, B and C. Values of variables A, B and C either 1 or
0 based on the information if "Neeraja" has visited the corresponding shop or not. Therefore, X
will store the number of distinct shops visited by Neeraja.

Question 7 [5 Marks]
Statement
The following procedure is executed using the "Words" dataset. At the end of execution, count
stores the number of words with Part of speech "Noun" and Letter count greater than or equal to
4. But the programmer may have made mistakes in one or more steps. Identify all such steps (if
any). It is a Multiple Select Question (MSQ).

Step 1: Arrange all cards in a single pile called Pile 1

Step 2: Maintain a variable count and initialize it to 1

Step 3: If Pile 1 is empty then stop the iteration

Step 4: Read the top card in Pile 1

Step 5: If Part of speech is "Verb" and Letter count >= 4 then increment count

Step 6: Move the current card to another pile called Pile 2 and repeat from step 3
Options
(a)

Step 2: Incorrect initialization of the variable count

(b)

Step 3: Incorrect step for stopping the iteration

(c)

Step 5: Incorrect condition to update count

(f)

No mistake

Answer
(a) and (c)

Solution
As we all know that the counting always start from 1 therefore initial value of variable count
should be 0. Hence, step 2 is incorrect. Now, as per the given statement we are looking for nouns,
not verbs therefore step 5 is also incorrect.
Question 8 [5 Marks]
Statement
The given information represents a "Scores" dataset and it may have some mistakes with respect
to the sanity of data. Identify all rows with such mistakes. It is a Multiple Select Question (MSQ).

Row no. Field Value

Row 1 Card number Harish

Row 2 Name 1

Row 3 Gender M

Row 4 Date of Birth 30 February

Row 5 Mathematics 662

Row 6 Physics 45

Row 7 Chemistry 91

Row 8 Total 398

Options
(a)

Row 1: Incorrect data type of card number

(b)

Row 2: Incorrect data type of Name

(c)

Row 3: Incorrect data type of Gender

(d)

Row 4: Invalid Date of Birth

(e)

Row 5: Mathematics score is out of range

(f)

Row 6: Physics score is out of range


(g)

Row 7: Chemistry score is out of range

(h)

Row 8: Total score is out of range

Answer
(a), (b), (d), (e) and (h)

Solution
Row 1 is incorrect because it should be a number.

Row 2 is incorrect because 1 is not a valid name.

Row 4 in incorrect because 30 February is not a valid date.

Row 5 in incorrect because the marks are above 100, which is not valid.

Row 8 is incorrect because the total marks are above 300 which is not valid.

Question 9 [5 Marks]
Statement
Match the following by selecting the most appropriate datatype specific to "Scores" dataset for
the left column.

Field name Datatype

1. Gender of a student i. Integer

2. Name of a student ii. Boolean

3. Marks of a subject iii. String

4. City of a student iv. Character

Options
(a)

1: iv, 2: iii, 3: i, 4: iv

(b)

1: i, 2: iii, 3: i, 4: iii
(c)

1: iv, 2: iii, 3: i, 4: iii

(d)

1: i, 2: iii, 3: i, 4: iv

Answer
(c)

Solution
1. Gender of a student is either 'M' or 'F', which is a single character enclosed in single quotes,
Hence it a character
2. Name of a student is a sequence of character in double quotes, it is a string.
3. Marks of subject is a number. Hence, it is an integer.
4. City of a student is a sequence of character in double quotes, it is a string.

Question 10 [5 Marks]
Statement
Interpret the following flowchart and answer the questions. Let A, B and C be three distinct
integers given as input.
What will X represent at the end of flowchart?

Options
(a)

Median among A, B and C

(b)

Second largest number among A, B and C

(c)

Largest among A, B and C

(d)

Smallest among A, B and C

Answer
(c)
Solution
Three input variables A, B and C are given. Then the variable X is initialized to 0.

Condition 1: If A > B is True -

Condition 1.1: If C > A is True - This means A > B and C > A. Combining both the condition C > A
> B. Here X = C which means the largest value among these three numbers.

Condition 1.2: If C > A is False- This means A > B and A >=C (but all are distinct integers there
fore A > C). If X = A then again largest value among these three numbers.

Condition 2: If A > B is False-(Means B > A)

Condition 2.1: If C > B is True - This means C > B and B > A. Combining both the condition C > B
> A. Here X = C which means the largest value among these three numbers.

Condition 2.2: If C > B is False- This means B > A and B > C. If X = B then again the largest value
among these three numbers.
Computational Thinking
Week - 3
Graded Assignment
1. In the “Shopping Bills” dataset, the procedure countBills counts the number of bills from Big
Bazaar with total amount more than the average total bill amount. Assume that the variable
Avg holds the value of the average total bill amount. Choose the correct code fragments to
complete the procedure. It is a Multiple Select Question (MSQ). [4 Marks]

Procedure countBills ( )
Count = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
*********************
* Fill the code *
*********************
Move card X to Pile 2
}
return (Count)
End countBills

a.
if (X.ShopName == “BigBazaar”) {
if (X.TotalBillAmount > Avg) {
Count = Count + 1
}
}
b.
if (X.TotalBillAmount > Avg) {
if (X.ShopName == “BigBazaar”) {
Count = Count + 1
}
}
c.
if (X.TotalBillAmount > Avg and X.ShopName == “BigBazaar”) {
Count = Count + 1
}
d.
if (X.TotalBillAmount < Avg and X.ShopName == “BigBazaar”) {
Count = Count + 1
}
e. None of the above
Computational thinking Week - 3 Page 2 of 9

2. The following pseudocode is executed using the “Scores” dataset. What will be the value of
the variable Z at the end of the execution? [4 Marks]

SumT = 0, SumM = 0, SumP = 0, SumC = 0


while (Pile 1 has more cards) {
Read the top card X from Pile 1
SumT = SumT + X.Total
SumM = SumM + X.Mathematics
SumP = SumP + X.Physics
SumC = SumC + X.Chemistry
Move card X to Pile 2
}
Z=0
if ((SumM + SumP + SumC)/SumT ≥ 0) {
Z=1
}
if ((SumM + SumP + SumC)/ SumT ≤ 1) {
Z = -1
}

a. 0
b. 1
c. -1
d. None of the above
Computational thinking Week - 3 Page 3 of 9

3. The following pseudocode is executed using the “Scores” dataset. At the end of the execution,
variable Count captures the number of students whose total marks are more than the class
average (of total marks) but have scored below the subject average in at least one subject.
Assume that the variable AvgT holds the value of the average total marks. Similarly, the
variables AvgP, AvgC and AvgM hold the value of the average marks of Physics, Chemistry
and Mathematics respectively. Choose the correct code fragment to complete the pseudocode.[4 Marks]
Count = 0
while (Table 1 has more rows) {
Read the first row X from Table 1
A = False, B = False, C = False, D = False
if (X.Total > AvgT) {
A = True
}
if (X.Mathematics < AvgM) {
B = True
}
if (X.Physics < AvgP) {
C = True
}
if (X.Chemistry < AvgC) {
D = True
}
*********************
* Fill the code *
*********************
}
Move X to Table 2
}
a.
if (A and (B or C or D)) {
Count = Count + 1
}
b.
if ((A or B) and (C or D)) {
Count = Count + 1
}
c.
if ((A and B) and (C or D)) {
Count = Count + 1
}
d.
if ((A and B) or (C and D)) {
Count = Count + 1
}
Computational thinking Week - 3 Page 4 of 9

4. The following pseudocode is executed using the “Shopping bills” dataset. What will the values
of the variables A and B represent at the end of the execution? [4 Marks]

SumSV = 0, SumBB = 0
CountSV = 0, CountBB = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
if (X.ShopName == “SV Stores”) {
SumSV = SumSV + X.TotalBillAmount
CountSV = CountSV + 1
}
if (X.ShopName == “Big Bazaar”) {
SumBB = SumBB + X.TotalBillAmount
CountBB = CountBB + 1
}
Move card X to Pile 2
}
MSV = SumSV / CountSV
MBB = SumBB / CountBB
A = 0, B = 0
while (Pile 2 has more cards) {
Read the top card X from Pile 2
if (X.ShopName == “SV Stores” and X.TotalBillAmount > MSV) {
A=A+1
}
if (X.ShopName == “Big Bazaar” and X.TotalBillAmount < MBB) {
B=B+1
}
Move card X to Pile 1
}

a. A = Number of bills from “Big Bazaar” with total bill amount greater than the average
total bill amount of “SV Stores”
B = Number of bills from “SV Stores” with total bill amount less than the average total
bill amount of “Big Bazaar”
b. A = Number of bills from “SV Stores” with total bill amount greater than the average
total bill amount of “SV Stores”
B = Number of bills from “Big Bazaar” with total bill amount less than the average total
bill amount of “Big Bazaar”
c. A = Number of bills from “SV Stores” with total bill amount less than the average total
bill amount of “Big Bazaar”
B = Number of bills from “Big Bazaar” with total bill amount greater than the average
total bill amount of “SV Stores”
d. A = Number of bills with total bill amount greater than the average total bill amount
B = Number of bills with total bill amount less than the average total bill amount
Computational thinking Week - 3 Page 5 of 9

5. The following pseudocode is executed using the “Scores” dataset. Assume that the variable
AvgP holds the average Physics marks. What will be the values of CountA, CountB,
CountC and CountD at the end of the execution? Fractions can be rounded to next nearest
integer. For example 50.1 and 50.9 can be rounded to 51. [4
8 Marks]

AvgP = 73
Mid2 = 1.25*AvgP
Mid1 = 0.75*AvgP
CountA = 0, CountB = 0, CountC = 0, CountD = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
if (X.Gender == “F” ) {
if (X.Physics ≥ Mid2) {
CountA = CountA + 1
}
if (X.Physics < Mid2 and X.Physics ≥ AvgP) {
CountB = CountB + 1
}
if (X.Physics < AvgP and X.Physics ≥ Mid1) {
CountC = CountC + 1
}
if (X.Physics < Mid1) {
CountD = CountD + 1
}
}
Move card X to Pile 2
}

CountA = , CountB = , CountC = and CountD = (Numerical input)


Computational thinking Week - 3 Page 6 of 9

6. The following pseudocode is executed using the “Scores” dataset. What will count represent
at the end of execution? [4 Marks]

count = 0
while (Table 1 has more rows) {
Read the first row X in Table 1
Move the row X to Table 2
while (Table 1 has more rows) {
Read the first row Y in Table 1
count = count + compareSomething(X.Total, Y.Total )
count = count + compareSomething(Y.Total, X.Total )
Move the row Y to Table 3
}
Move all rows from Table 3 to Table 1
}
Procedure compareSomething(A, B)
if (A > B) {
return (-1)
}
else {
return (1)
}
End compareSomething

a. Number of pairs of students who have different total marks


b. Number of pairs of students who have same total marks
c. Twice the number of pairs of students who have different total marks
d. Twice the number of pairs of students who have same total marks
e. It is always zero
Computational thinking Week - 3 Page 7 of 9

7. The following pseudocode is executed using the “Shopping bills” dataset to find the number
of eligible bills for the lowest three total bill amounts. Choose the correct code fragment to
complete the pseudocode. [4 Marks]

FirstT = 10000, SecondT = 10000, ThirdT = 10000


while (Pile 1 has more cards) {
Read the top card X from Pile 1
if (X.TotalBillAmount < FirstT) {
ThirdT = SecondT
SecondT = FirstT
FirstT = X.TotalBillAmount
}
if (X.TotalBillAmount > FirstT and X.TotalBillAmount < SecondT) {
ThirdT = SecondT
SecondT = X.TotalBillAmount
}
if (X.TotalBillAmount > SecondT and X.TotalBillAmount < ThirdT) {
ThirdT = X.TotalBillAmount
}
Move card X to Pile 2
}
Count = 0
while (Pile 2 has more cards) {
Read the top card X from Pile 2
*********************
* Fill the code *
*********************
Move card X to Pile 1
}

a.
if (X.TotalBillAmount < ThirdT) {
Count = Count + 1
}
b.
if (X.TotalBillAmount ≤ ThirdT) {
Count = Count + 1
}
c.
if (X.TotalBillAmount > ThirdT) {
Count = Count + 1
}
d.
if (X.TotalBillAmount ≥ ThirdT) {
Count = Count + 1
}
e. None of the above
Computational thinking Week - 3 Page 8 of 9

8. The following pseudocode is executed using the “Scores” dataset. Let minTotal stores the
minimum total marks obtained by any student. What will the value of Flag at the end of the
execution? [4 Marks]

A = 101, B = 101, C = 101, D = 101


Flag = False
while (Pile 1 has more cards) {
Read the top card X from Pile 1
A, B, C = doSomething(X, A, B, C)
Move X to Pile 2
}

D=A+B+C
if ((minTotal − D) ≥ 0) {
Flag = True
}

Procedure doSomething(Y, A, B, C) {
if (Y.Mathematics < A) {
A = Y.Mathematics
}
if (Y.Physics < B) {
B = Y.Physics
}
if (Y.Chemistry < C) {
C = Y.Chemistry
}
return ([A, B, C])
End doSomething

a. False
b. True
c. Not sure
Computational thinking Week - 3 Page 9 of 9

9. The following pseudocode is executed using the “Scores” dataset. At the end of the execution,
CountM captures the number of male students whose Mathematics marks are less than the
average Mathematics marks of female students. But the pseudocode may have mistakes in one
or more lines. Identify all such lines (if any). It is a Multiple Select Question (MSQ). [4 Marks]

1 Sum = 0, Count = 0
2 while (Pile 1 has more cards) {
3 Read the top card X in Pile 1
4 Sum, Count = addMarks(X, Sum, Count)
5 Move card X to Pile 2
6 }
7 AvgT = Sum / Count
8 CountM = 0
9 while (Pile 2 has more cards) {
10 Read the top card X in Pile 2
11 if (X.Mathematics < AvgT) {
12 CountM = CountM + 1
13 }
14 Move card X to Pile 1
15 }

16 Procedure addMarks (Y, SumF, CountF)


17 if (Y.Gender == ‘F’) {
18 SumF = SumF + Y.Mathematics
19 CountF = CountF +1
20 }
21 return ([SumF, CountF])
22 End addMarks

a. Error in Line 4
b. Error in Line 11
c. Error in Line 17
d. Error at Line 18
e. Error in Line 21
f. No error in the code
1. The following pseudocode is executed using the “Scores” dataset. It computes the number of
students in each grade, where grades are assigned based on total marks. Choose the correct
code block to complete the pseudocode.
Min = 100, Max = 0
while (Table 1 has more rows) {
Read the first row X in Table 1
if (X.Total > Max) {
Max = X.Total
}
if (X.Total < Min) {
Min = X.Total
}
Move X to Table 2
}
Interval = (Max - Min) / 3
Mid2 = Max - Interval
Mid1 = Mid2 - Interval
countA = 0, countB = 0, countC= 0
while (Table 2 has more rows) {
Read the first row X in Table 2
if (X.Total ≤ Mid1) {
countC = countC + 1
}
*********************
* Fill the code *
*********************
if (X.Total > Mid2) {
countA= countA + 1
}
}

a.
if (X.Total > Mid1) {
countB = countB + 1
}
b.
if (X.Total ≤ Mid2 and X.Total ≥ Mid1) {
countB = countB + 1
}
c.
if (X.Total > Mid1 and X.Total ≤ Mid2) {
countB = countB + 1
}
d.
if (X.Total ≥ Mid1 and X.Total < Mid2) {
countB = countB + 1
}
2. The following pseudocode is executed using the “Words” dataset. Let A and B be the variables
that hold the values of letter counts of shortest and longest word, respectively. What will count
represent at the end of execution?

count = 0
while (Table 1 has more cards) {
Read the first row X from Table 1
Move X to Table T2
if (X.Word ends with a full stop) {
count = count + DoSomething (Table T2, A, B)
}
}

Procedure DoSomething (Table 2, X, Y)


C = 0, D = 0
while (Table 2 has more rows) {
Read the first row Z from Table 2
if (Z.LetterCount ≤ X) {
C=1
}
if (Z.LetterCount ≥ Y) {
D=1
}
Move Z to Table 3
}
if (C + D == 1) {
return (1)
}
else {
return (0)
}
End DoSomething

a. Number of sentences having exactly one shortest word or exactly one longest word
b. Number of sentences having exactly one shortest word and exactly one longest word
c. Number of sentences having at least one shortest word or at least one longest word
d. Number of sentences having at least one shortest word or at least one longest word but
not both
e. None of the above
3. The following pseudocode is executed using the “Shopping bills” dataset. Assume that the
variable Avg holds the value of the average total bill amount. The procedure countSomething
counts the number of bills that are not from BigBazaar and with total bill amount greater than
Avg. Choose the correct code fragment to complete the procedure. It is a Multiple Select
Question (MSQ).

Procedure countSomething ( )
count = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
*********************
* Fill the code *
*********************
Move card X to Pile 2
}
return (count)
End countSomething

a.
if (X.ShopName == “BigBazaar”) {
if (X.TotalBillAmount > Avg) {
count = count + 1
}
}
b.
if (X.ShopName 6= “BigBazaar”) {
if (X.TotalBillAmount < Avg) {
count = count + 1
}
}
c.
if (X.ShopName 6= “BigBazaar”) {
if (X.TotalBillAmount > Avg) {
count = count + 1
}
}
d.
if (X.ShopName 6= “BigBazaar” and X.TotalBillAmount > Avg) {
count = count + 1
}
}
e. None of the above
4. The following pseudocode is executed using the “Words” dataset. What will A and B represent
at the end of execution?

sum = 0, count = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
sum = sum + X.LetterCount
count = count + 1
}
Move card X to Pile 2
}
MLC = sum/count
A = 0, B = 0
while (Pile 2 has more cards) {
Read the top card X from Pile 2
if (X.PartsOfSpeech == “Noun” and X.LetterCount ≤ MLC) {
A=A+1
}
if (X.PartsOfSpeech == “Verb” and X.LetterCount ≥ MLC) {
B=B+1
}
Move card X to Pile 1
}

a. A = Number of nouns with letter count less than the average letter count
B = Number of verbs with letter count greater than the average letter count
b. A = Number of words with letter count less than the average letter count
B = Number of words with letter count greater than the average letter count
c. A = Number of nouns having letter count less than or equal to average letter count
B = Number of verbs having letter count greater than or equal to average letter count
d. A = Number of nouns having letter count greater than or equal to average letter count
B = Number of verbs having letter count greater than or equal to average letter count
5. The following pseudocode is executed using the “Scores” dataset. What will count represent
at the end of the execution? It is a Multiple Select Question (MSQ).

count = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
count = count + doSomething(X)
Move card X to Pile 2
}
Procedure doSomething (X)
if (X.Mathematics < X.Physics or X.CityTown == “Chennai”) {
return (1)
}
return (0)
End doSomething

a. Number of Chennai students whose Mathematics marks are less than Physics marks
b. Number of Chennai students + Number of students whose Mathematics marks are less
than Physics marks.
c. Number of Chennai students whose Mathematics marks are greater than or equal to
Physics marks + Number of students whose Mathematics marks are less than Physics
marks
d. Number of Chennai students + Number of students not from Chennai whose Mathematics
marks are less than Physics marks
e. None of the above
6. The following pseudocode is executed using the “Words” dataset. At the end of execution of
the pseudocode, countB captures the number of verbs whose letter count is strictly greater
than the average letter count of verbs. But the pseudocode may have mistakes in one or more
lines. Identify all such lines (if any). It is a Multiple Select Question (MSQ).

1 sum = 0, count = 0
2 while (Pile 1 has more cards) {
3 Read the top card X in Pile 1
4 sum, count = addIfVerb(X)
5 Move card X to Pile 2
6 }
7 Avg = sum / count
8 countB = 0
9 while (Pile 2 has more cards) {
10 Read the top card X in Pile 2
11 if (X.LetterCount ≥ Avg and X.PartOfSpeech == “Verb”) {
12 countB = countB + 1
13 }
14 Move card X to Pile 1
15 }
16 Procedure addIfVerb (Y, sumV, countV)
17 if (Y.PartOfSpeech == “Verb”) {
18 sumV= sumV + Y.LetterCount
19 countV = 1
20 }
21 return ([sumV, countV])
22 End addIfVerb

a. Error in Line 4
b. Error in Line 7
c. Error in Line 11
d. Error at Line 12
e. Error in Line 17
f. Error at Line 18
g. Error at Line 19
h. Error in Line 21
i. No error in the code
7. The following pseudocode is executed using the “Scores” dataset. What will the value of count
represent at the end of execution?

A = 0, B = 0, C = 0, count = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
A, B, C = doSomething(X, A, B, C)
Move X to Pile 2
}
while (Pile 2 has more cards) {
Read the top card Y from Pile 2
if (Y.Mathematics == A and Y.Physics == B and Y.Chemistry == C) {
count = count + 1
}
Move Y to Pile 1
}
Procedure doSomething(Y, A1, B1, C1) {
if (A1 < Y.Mathematics) {
A1 = Y.Mathematics
}
if (B1 < Y.Physics) {
B1 = Y.Physics
}
if (C1 < Y.Chemistry) {
C1 = Y.Chemistry
}
return ([A1, B1, C1])
End doSomething

a. Number of students who scored the lowest marks in any one of three subjects.
b. Number of students who scored the lowest marks in all three subjects.
c. Number of students who scored the highest marks in all three subjects.
d. Number of students who scored the highest marks in any one of three subjects.
8. The following pseudocode is executed using the “Words” dataset. What will A and B represent
at the end of execution?

Procedure countSomething ( )
A = 0, B = 0
while (Pile 1 has more cards) {
Read the top card X from Pile 1
if (X.PartOfSpeech 6= “Noun”) {
if (X.LetterCount 6= 6) {
A=A+1
}
}
else {
if (X.LetterCount == 6) {
B=B+1
}
}
Move card X to Pile 2
}
return ([A, B])
End countSomething

a. A = Number of nouns with letter count not equal to 6


B = Number of words with letter count equal to 6
b. A = Number of words other than nouns with letter count equal to 6
B = Number of words with letter count equal to 6
c. A = Number of words other than nouns with letter count not equal to 6
B = Number of nouns with letter count equal to 6
d. A = Number of words other than nouns with letter count not equal to 6
B = Number of words with letter count equal to 6
9. The following pseudocode is executed using the “Scores” dataset. When will Flag be set to
True?

A = 0, B = 0, Flag = False
while (Pile 1 has more cards) {
Read the top card X from Pile 1
if (X.Gender == ‘M’) {
if (X.CityTown == “Madurai”) {
A=A+1
}
}
else {
if (X.CityTown == “Bangalore”) {
B=B+1
}
}
Move card X to Pile 2
}
if (A > B) {
Flag = True
}

a. If number of male students from Madurai is greater than the number of students from
Bangalore.
b. If number of male students from Madurai is greater than the number of female students
from Bangalore.
c. If number of male students from Madurai is less than the number of students from
Bangalore.
d. If the number of male students is greater than that of number of female students
Computational Thinking
CT-Jan-2022-Week4GradedAssignment Solution
Total Points: 45 Duration:

1. For which of the following situation(s) is/are a nested loop needed? It is a Multiple Select
Question (MSQ).

a. To find the pair of students who have the same birthdays from the “Scores” dataset
b. To find the pair of students who scored the same marks in Physics from the “Scores”
dataset
c. To find the number of words which have highest letter count from the “Words” dataset
d. To find the number of bills from the same shop from the “Shopping Bills” dataset

Answer: a, b
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 2 of 25

Solution: In the above question we have to find the situations where nested loop is
required. Therefore we will go through the each options.
Option a): We need a nested loop for finding the pair of students who have the same
birthdays. The outer loop (while) will select a card from the dataset and the inner loop
(while) will compare this card with the remaining cards in the dataset for the same birthday.
The pseudocode can be:

count = 0
while(Table 1 has more rows) {
Read the top row X from the Table 1
Move X to the Table 2
while (Table 1 has more rows) {
Read the top row Y from the Table 1
if (X.DateOfBirth == Y.DateOfBirth) {
count = count + 1
}
Move Y to Table 3
}
Move all rows from Table 3 to Table 1
}

Option b): In this situation we also need a nested loop for finding the pair of students
who scored same marks in Physics. The outer loop (while) will select a card from the
dataset and the inner loop (while) will compare this card with the remaining cards in the
dataset for the same marks in Physics. The pseudocode can be:

count = 0
while(Table 1 has more rows) {
Read the top row X from the Table 1
Move X to Table 2
while (Table 1 has more rows) {
Read the top row Y from Table 1
if (X.Physics == Y.Physics) {
count = count + 1
}
Move Y to the Table 3
}
Move all rows from Table 3 to Table 1
}

Option c): A single loop can find the number of the words which have highest letter count
from the ”Scores” dataset. The pseudocode can be:
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 3 of 25

max = 0, count = 0
while(Table 1 has more rows) {
Read the top row X from Table 1
if (X.LetterCount == max) {
count = count + 1
}
if (X.LetterCount > max) {
max = X.LetterCount
count = 0
}
Move X to Table 2
}

Option d): In this case, a single loop can find the numbers of bills from the same shop
from the ”Shopping Bills” dataset. Assume we want to find the number of bills from Big
Bazaar. The pseudocode can be:

count = 0
while(Table 1 has more rows) {
Read the top row X from Table 1
if (X.ShopName == “Big Bazaar”) {
count = count + 1
}
Move X to the Table 2
}

Therefore, a) and b) are the correct options.


Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 4 of 25

2. The following pseudocode is executed using the “Words” dataset. At the end of the execution,
A captures the number of sentences with at least two nouns that have at most two vowels.
Choose the correct code fragments to complete the pseudocode.

1 A = 0, C = 0
2 while (Table 1 has more rows) {
3 Read the first row X from Table 1
4 if (X.PartOfSpeech == “Noun” and countVowels(X) ≤ 2) {
5 C=C+1
6 }
7 if (X.Word ends with a full stop) {
8 if (C ≥ 2) {
9 A=A+1
10 *** Statement1 ***
11 }
10 *** Statement2 ***
12 }
13 Move X to Table 2
14 }

15 Procedure countVowels (Y)


16 i=1
17 B=0
18 while (i ≤ Y.LetterCount) {
19 if (ith letter of Y.Word is a vowel) {
20 B=B+1
21 *** Statement3 ***
22 }
23 *** Statement4 ***
23 }
24 return (B)
25 End countVowels

a. Statement1: Not necessary


Statement2: C=0
Statement3: Not necessary
Statement4: i=i+1
b. Statement1: Not necessary
Statement2: C=0
Statement3: i=i+1
Statement4: Not necessary

c. Statement1: Not necessary


Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 5 of 25

Statement2: C = C + 1
Statement3: Not necessary
Statement4: i = i + 1
d. Statement1: C=0
Statement2: Not necessary
Statement3: Not necessary
Statement4: i=i+1

Answer: Option a
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 6 of 25

Solution: In the first section of code a card is picked up and C is being incremented if the
card has two properties. First it is a noun and the second countVowels(X) ≤ 2, Which
means countVowels(X) is supposed to return number of vowels in the selected card (row).

In the procedure countVowels(X), i is initialized to 1 (the first letter of word) and B


is initialized to 0 (number of vowels seen so far). In while block, to iterate through the
words’ letters, i should be incremented in the last. Therefore, Statement4: i = i + 1.
In the condition box, B is being incremented whenever a vowel is seen. Therefore, no
requirement of Statement3 i.e., Stetement3 : Not Necessary.

As we are concerned about a sentence, the second condition block of first section of code
is checking if the word ends with a full stop. A is being incremented if there are at least
two required words, which means there is no requirement of Statement1 i.e., Statement1 :
Not Necessary. As C is sentence specific variable it must be reinitialized to zero, once the
sentence ends. Therefore, Statement2 : C = 0.

Therefore, Option a is correct option.


Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 7 of 25

3. The following pseudocode is executed using the “Library” dataset. At the end of the execution,
N captures the name of a book which has the maximum number of pages and is written in a
language other than English, and A captures the number of pages in the book.

A = 0, N = “None”
while (Table 1 has more rows) {
Read the first row X in Table 1
if (X.Language ̸= “English” and X.Pages > A) {
A = X.Pages
N = X.Name
}
Move X to Table 2
}

If the rows of the table are shuffled in any random order, then choose the correct option(s). It
is a Multiple Select Question (MSQ).

a. There will be no change in N, irrespective of the order of rows.


b. There might be a change in N, based on the order of rows.
c. There will be no change in A, irrespective of the order of rows.
d. There might be a change in A, based on the order of rows.

Answer: Options b and c


Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 8 of 25

Solution: Let there are two books, book1 and book2 having the maximum number of
pages (say n, i.e., both have same number of pages, n) in the library dataset. If book1 is
kept before book2 then A will store n and N will store book1 as we are not checking the
equality condition i.e., X.pages ≥ A (we are checking only X.pages > A). If the order is
reversed, then A will store n but N will store book2.
Therefore, N depends on the order of the books while A does not.

Therefore, Options b and c are the correct options.


Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 9 of 25

4. The given pseudocode is executed using the “Shopping Bills” dataset. frac stores the ratio of
the number of customers who purchased both “Bread” and “Milk” to the number of customers
who purchased “Milk”. Choose the correct code fragment to complete the pseudocode. (Assume
there is at least one customer who has purchased “Milk”).

mCount = 0, bCount = 0
While (Pile 1 has more cards) {
Read the top card X in Pile 1
*********************
* Fill the code *
*********************
Move X to Pile 2.
}
frac = bCount / mCount

Procedure isItem (Y, A)


C = False
while (Card Y has more items) {
Read an item Z from ItemList of card Y
if (Z.Item == A) {
C = True
}
Remove Z from ItemList of Y
}
return(C)
End isItem

a.
if (isItem(X, “Milk”)) {
mCount = mCount + 1
}
if (isItem(X, “Bread”)) {
bCount = bCount + 1
}
b.
if (isItem(X, “Bread”)) {
bCount = bCount + 1
if (isItem(X, “Milk”)) {
mCount = mCount + 1
}
}
c.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 10 of 25

if (isItem(X, “Milk”) and isItem(X, “Bread”)) {


mCount = mCount + 1
bCount = bCount + 1
}
d.
if (isItem(X, “Milk”)) {
mCount = mCount + 1
if (isItem(X, “Bread”)) {
bCount = bCount + 1
}
}
Answer: Option d
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 11 of 25

Solution:
Procedure isItem (Y, A) returns True if item A is there in the item list of card Y
otherwise returns False. As we are trying to find the number of customers who purchased
both Bread and Milk to the number of customers who purchased Milk, bCount stores the
number of customers who buy Bread and Milk together and mCount stores the number
of customers who buy Milk.

Option a. bCount stores the number of customers who buy Bread (irrespective of the
customers who buy Milk or not). This is not the case here.

Option b. mCount stores the number of customers who buy Milk only if they buy Bread.
This is not the case here.

Option c. bCount and mCount are always same and stores the number of customers
who buy both Bread and Milk. This is not the case here.

Option d. bCount stores the number of customers who buy Bread only if they buy Milk.
Therefore, option d is correct.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 12 of 25

5. The following pseudocode is executed using the “Scores” dataset. Two students form a study
pair if their difference in Mathematics marks are at most 10. Assume that Pile P1 is always
restored back after calling studyPair(Pile P1)

count1 = studyPair(Pile 1)
while (Pile 1 has more cards) {
Read the first card X in Pile 1
if (X.CityTown == “Chennai”) {
Move X to Pile CHN
}
if (X.CityTown == “Bengaluru”) {
Move X to Pile BLR
}
if (X.CityTown == “Vellore”) {
Move X to Pile VLR
}
}
count2 = studyPair(Pile CHN) + studyPair(Pile BLR) + studyPair(Pile VLR)
count3 = count1 - count2

Procedure studyPair(Pile P1)


A=0
while (Pile P1 has more cards) {
Read the first card in Pile P1
Move X to Pile P2
while (Pile P1 has more cards) {
Read the first card in Pile P1
Move Y to Pile P3
if (-10 ≤ X.Mathematics – Y.Mathematics ≤ 10) {
A=A+1
}
}
Move all cards from Pile P3 to Pile P1
}
return(A)
End studyPair
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 13 of 25

(a) What will count1 represent at the end of execution?


a. Number of study pairs
b. Number of pairs of study pair
c. Number of students who formed study pairs
d. Number of study pairs from the same city
Answer: Option a

(b) What will count3 represent at the end of execution?


a. Number of study pairs where at least one student in each pair is not from the cities
Chennai, Bengaluru, and Vellore
b. Number of study pairs where both the students in each pair are not from the same
city among Chennai, Bengaluru and Vellore
c. Number of study pairs where students in each pair are from different cities among
Chennai, Bengaluru and Vellore
d. Number of study pairs where students in each pair are from the same city among
Chennai, Bengaluru and Vellore
Answer: Option b
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 14 of 25

Solution: studyPair(Pile P1) returns the number of study pairs (X, Y) formed from
Pile P1, where marks difference between X and Y is maximum 10.

count1 is the total number of study pairs formed. Therefore, Option a is the correct
answer for first part of the question.

Pile CHN is the pile created from the students of Chennai. Therefore, studyPair(Pile
CHN) returns the number of study pairs (X, Y) formed where X and Y both are from
Chennai.

Similarly count2 is the number of study pairs (X, Y) formed, where either X and Y both
are from Chennai or X and Y both are from Bengalure or X and Y both are from Vellore.
In simple words count2 is the number of study pairs where both the students in a pair
are from same city among cities Chennai, Bengaluru, and Vellore.

count3 = count1 - count2. Therefore, count3 is just the negation of count2 i.e.,
number of study pairs where both the students in a pair are not from same city among
cities Chennai, Bengaluru, and Vellore. The possible examples are (Keral, Vellore), (Erode,
Salem), (Chennai, Bengaluru) etc.

There is option c which looks like option b but it says Number of study pairs where students
in each pair are from different cities among Chennai, Bengaluru, and Vellore. Which means
both the students must belong to at least one of the cities among Chennai, Bengaluru, and
Vellore but not from same city. Therefore, (Keral, Vellore) will not be a pair according to
option c.

Therefore, Option b is the correct option for the second part of the question.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 15 of 25

6. The following pseudocode is executed using the “Words” dataset.

count = 0
while (Table 1 has more rows) {
Read the first row X in Table 1
Move X to Table 2
i = 1, A = False, B = False
while (i ≤ X.LetterCount) {
if (ith letter of X.Word is a vowel) {
if (A) {
B = True
}
A = True
}
else {
A = False
}
i=i+1
}
if (B) {
count = count + 1
}
}

What will count represent at the end of execution?

a. Number of words with at least one pair of vowels occurring consecutively


b. Number of words with at most two pairs of vowels occurring consecutively
c. Number of words with at least two pairs of the same vowel occurring consecutively
d. Number of words with at most two pairs of the same vowel occurring consecutively

Answer: Option a
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 16 of 25

Solution: The above pseudocode is executed on the “Words” dataset and we are required
to find what count represents at the end of execution. From the pseudocode we can
conclude that count will only be incremented when B is True.
To understand the above pseudocode let us choose a word “value”, and go through the
pseudocode with this word.

letter i=1 A = False B = False count = 0


v 1 False False 0
a 2 True False 0
l 3 False False 0
u 4 True False 0
e 5 True True 1

From the above created table for the word “value”, B holds True and B will not be updated
once it becomes True for a word. That means count will be incremented for the word
with at least one pair of vowels occurring consecutively.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 17 of 25

7. The following pseudocode is executed using the “Scores” dataset. At the end of the execution,
A, B and C capture the number of pairs of students who scored at most 200, from 201 to 250
and at least 251, respectively who are from the same city but are of different gender. Choose the
correct code fragment(s) to complete the pseudocode. It is a Multiple Select Questions(MSQ)

A = 0, B = 0, C = 0
while (Table 1 has more rows) {
Read the first row X in Table 1
if (X.Total ≤ 200) {
Move X to Table 2
}
if (X.Total ≥ 201 and X.Year ≤ 250){
Move X to Table 3
}
if (X.Total ≥ 251) {
Move X to Table 4
}
}

A = similarTotal(Table 2)
B = similarTotal(Table 3)
C = similarTotal(Table 4)

Procedure similarTotal(Table T1)


D=0
while (Table T1 has more rows) {
Read the first row Y in Table T1
Move Y to Table T2
while (Table T1 has more rows) {
Read the first row Z in Table T1
Move Z to Table T3
*****************************
* Fill the code *
*****************************
}
Move all rows from Table T3 to Table T1
}
return(D)
End similarTotal

a.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 18 of 25

if (Y.CityTown == Z.CityTown){
if (Y.Gender ̸= Z.Gender ){
D=D+1
}
}
b.
if (Y.Gender ̸= Z.Gender ){
if (Y.CityTown == Z.CityTown){
D=D+1
}
}
c.
if (Y.CityTown == Z.CityTown or Y.Gender ̸= Z.Gender ){
D=D+1
}
d.
if (Y.CityTown == Z.CityTown and Y.Gender ̸= Z.Gender ) {
D=D+1
}
Answer: Option a, b, d
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 19 of 25

Solution:
The above pseudocode is executed on the “Scores” dataset. At the end of the execution,
variables A , B and C capture the number of pairs of students who scored scored at most
200, from 201 to 250 and at least 251, respectively, who are from the same city but of
different gender. But the pseudocode has to be completed with the correct code fragment
from the given options. Let us observe the given pseudocode.
In the main part of the pseudocode, three bins are created based on the total marks. The
first bin i.e. Table 2 stores the students who scored at most 200 marks in total, the second
bin i.e. Table 3 stores the students who scored from 201 to 250 marks in total and the
third bin i.e. Table 4 stores the students who scored at least 251 marks in total. Then
procedure similarTotal is called separately with created bins as an input (argument).
The procedure similarTotal contains a nested while loop. This nested while loop should
create pairs of students from the created bins as mentioned in the problem. The condition
for checking the same city and different gender should be in the inner while loop of the
procedure similarTotal. The missing code fragment can be written as:

if (Y.CityTown == Z.CityTown and Y.Gender ̸= Z.Gender ) {


D=D+1
}

Here two conditions are connected with word “and”, which could be converted in two
conditions using nested loop which is given in option a and b. Therefore, options a, b, and
d are correct.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 20 of 25

8. The given pseudocode is executed using “Scores” dataset. Let B be a positive integer value.
What does the procedure DoSomething compute?

Procedure DoSomething (B)


C = 0, D = 100
while (Table 1 has more rows) {
Read the first row X in Table 1
if (X.Chemistry > C) {
C = X.Chemistry
}
if (X.Chemistry < D) {
D = X.Chemistry
}
Move X to Table 2
}
if (C − D >= B) {
return (False)
}
else {
return (True)
}
End DoSomething

a. Outputs “True” if and only if the difference between the maximum Chemistry marks and
the minimum Chemistry marks is at least B
b. Outputs “True” if and only if the difference between the maximum Chemistry marks and
the minimum Chemistry marks is at most B
c. Outputs “True” if and only if the difference between the maximum Chemistry marks and
the second maximum Chemistry marks is at most B
d. Outputs “True” if and only if the difference between the maximum Chemistry marks and
the minimum Chemistry marks is less than B

Answer: Option d
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 21 of 25

Solution: Here the procedure DoSomething accepts the parameter B which is a positive
integer.

C is initialized with 0 and being updated with the Chemistry mark of a students where ever
the Chemistry mark of the student is more than the current value of C. Therefore, C stores
the maximum mark in Chemistry obtained by any student.

D is just the opposite of C which stores the minimum marks in Chemistry obtained by any
student.

procedure DoSomething returns False when C - D is greater than or equal to B i.e., at least
B. Therefore, it returns True whenever the difference between maximum Chemistry marks and
the minimum Chemistry marks is less than B. Therefore, Option d is correct.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 22 of 25

9. The following pseudocode is executed using the “Words” dataset. At the end of the execution,
C captures the number of nouns with letter count at least four and at most eight. But the
pseudocode may have mistakes. Identify all such mistakes (if any). Assume that all statements
not listed in the options below are free of errors. It is a Multiple Select Question (MSQ).

1 C=0
2 while (Table 1 has more cards) {
3 Read the first row X from Table 1
4 if (CheckSomething(X, 4, 8)) {
5 C=C+1
6 }
7 Move X to Table 2
8 }

9 Procedure CheckSomething (Y, C1, C2,)


10 if (Y.PartOfSpeech == “Noun”) {
11 if (C1 ≤ Y.LetterCount and Y.LetterCount ≤ C2) {
12 return (True)
13 }
14 else {
15 return (False)
16 }
17 }
18 else {
19 return (True)
20 }
21 End CheckSomething

a. Line 4: Incorrect parameters used to call the procedure


b. Line 5: C is wrongly updated
c. Line 11: Incorrect conditional statement
d. Line 19: Incorrect value for return
e. No error

Answer: Option d
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 23 of 25

Solution: Here C captures the number of nouns with letter count at least four and at
most eight.

In the pseudocode, C is being incremented when CheckSomething(X, 4, 8) returns


True. Therefore, CheckSomething(Y, C1, C2) should return True whenever, Y.Word
is a noun and the letter count of Y.Word is between 4 and 8 including the boundaries.

At Line 4, the correct parameters are used to call the procedure and C is being incremented
at line 5. Therefore, Line 4 and Line 5 are correct.

In the procedure, Line 10 and Line 11 are the nested filters and contains the correct filters.
If these conditions are satisfied the procedure should return True which is being done here.
But if any of these two conditions fails, the procedure should return False, which is correct
in Line 15 but it is incorrect in Line 19. Therefore, there is an error in Line 19. Which
means, the correct option is d only.
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 24 of 25

10. The following pseudocode is executed using the “Library” dataset. At the end of the execution,
A captures the number of pairs of books which are published in the same genre and in the
same year but in different languages. But the pseudocode may have mistakes. Identify all such
mistakes (if any). Assume that all statements not listed in the options below are free of errors.
It is a Multiple Select Question (MSQ).

1 A=0
2 while (Table 1 has more cards) {
3 Move X to Table 2
4 Read the first row X from Table 1
5 while (Table 1 has more rows) {
6 Read the first row Y from Table 1
7 B = False, C = False, D = True
8 if (X.Genre == Y.Genre) {
9 B = True
10 }
11 if (X.Year == Y.Year) {
12 C = True
13 }
14 if (X.Language == Y.Language) {
15 D = False
16 }
17 if (B and C and D) {
18 A=A+1
19 }
20 Move Y to Table 3
21 }
22 Move all rows from Table 3 to Table 1
23 }

a. Line 1: A is initialized with wrong value


b. Line 9: B is updated with wrong value
c. Line 12: C is updated with wrong value
d. Line 15: D is updated in wrong place
e. No errors

Answer: Option e
Computational thinking CT-Jan-2022-Week4GradedAssignment Solution Page 25 of 25

Solution: As A captures the number of pairs of books which are published in the same
genre and in the same year but in different languages. Therefore, it should be initialized
with 0. Line 1 is right.

Line 18: Will be executed when B, C, and D all are True.

Line 9: B is being True only when the genres are same and that is what is required.
Therefore, Line 9 is correct.

Line 12: C is being True only when the years are same and that is what is required.
Therefore, Line 12 is correct.

Line 15: D is being False when ever languages are same which means it is True only when
the languages are different and that is what is required. Therefore, Line 15 is correct.

Therefore, this code does not have any error.


BSCCS1001: Week-5, Graded Assignment

1. (2 points) In the “Scores” table, let S be the list of sequence numbers of rows which have
marks greater than 75 in at least one subject. What does the variable count represent
at the end of execution of the pseudocode given below?

count = 0
while (Table 1 has more rows) {
Read the first row X in Table 1
foreach c in S {
if (X.SeqNo == c) {
if (X.Mathematics < 75 and X.Physics < 75) {
count = count + 1
}
}
}
Move X to Table 2
}

Number of students who have scored less than 75 in both Mathematics and
Physics
Number of students who have scored more than 75 in Chemistry

Number of students who have scored less than 75 in both Mathematics and
Physics, but more than 75 in Chemistry
Number of students who have scored less than 75 in all three subjects

Solution: There is a nested iteration in the code. The interesting aspect is that the
outer loop is a “while” and the inner loop is a “foreach”. The outer loop is going
over the rows in the “Scores” table. For each row in the table, the inner loop is going
over the elements in the list S.
Inside the inner loop, we have two if-conditions that are nested. The outer if-
condition checks if the row X from the table and element c from the list corresponds
to the same student. If yes, then we move on and check if the mathematics and
physics marks of this student is less than 75. If that is true, then count is incre-
mented. But note that we are looking at elements in the list S. These elements are
the sequence numbers of students who have scored greater than 75 in at least one
subject.
So, we have the following observations:

• The student has scored greater than 75 in at least one subject. This constraint
comes from the sequence number being in the list S.

• The student has scored less than 75 in both mathematics and physics. This
comes from the inner if-condition.

Since these two conditions are nested, we have to look at those students who satisfy
both the conditions. If we take the second condition first, then we are looking at
students who have scored less than 75 in both mathematics and physics. Now we
bring in the first condition. The only way a student can satisfy this condition is if
he has scored greater than 75 in chemistry.
Putting things together, count represents the number of students who have scored
below 75 in both mathematics and physics, but above 75 in chemistry.

Page 2
2. (2 points) The following pseudocode is executed on the “Words” table. Assume that
the rows in Table 1 are sorted in the increasing order of sequence number. What does
the list L contain at the end of execution?

L=[]
A = “None”
Read the first row X in Table 1
A = X.PartOfSpeech
Move X to Table 2
while (Table 1 has more rows) {
Read the first row X in Table 1
if (X.PartOfSpeech == “Noun”) {
if (A == “Adjective”) {
L = L ++ [X.Word ]
}
}
A = X.PartOfSpeech
Move X to Table 2
}


The list of nouns that come immediately after an adjective.
The list of adjectives that come immediately after a noun.
The list of nouns that come immediately before an adjective.
The list of adjectives that come immediately before a noun.

Solution: Let us look at the first few lines. List L is initialized to the empty list
and variable A is initialized to “None”. At first sight, the next line about reading
the first row from table 1, looks a bit out of place. So far, we have only encountered
this particular line inside a loop. But nothing stops us from reading the first row
in the table outside a loop. As the rows have been sorted in the increasing order of
sequence number, we have the variable A store the part of speech of the first word
in the paragraph.
Now, we enter the while loop. There is a nested if-condition. The outer if-condition
checks if the part of speech of the current word is a noun. Whenever that is true,
we move on to the inner if-condition, which checks if the variable A stores the value
“Adjective”. If that is true, then the current word is appended to the list L.

Page 3
It becomes clear that we are appending nouns to the list L. This is because the outer
if-condition stipulates that the part of speech of X should be “Noun”. But we are
not adding all nouns to the list L. To see when we append a noun to the list, we
have to understand the role played by the variable A.
Once we get out of the nested if-block, variable A is assigned the part of speech of
the current word. So, in the next step of the iteration, the variable A will be storing
the part of speech of the previous word.
Let us summarize and look at the two conditions that have to be satisfied if the
current word has to be appended to the list L:

• The part of speech of the current word is “Noun”.

• The part of speech of the previous word is “Adjective”.

Therefore, the list L stores all nouns that come immediately after an adjective. Let
us now highlight a few features of this code that are worth noting:

• Notice that the while loop starts iterating from the second row in the table.
Why not start from the first row as usual? We start from the second row
because the first word in the paragraph has no previous word. So, it only
makes sense to start the iteration from the second row in the table.

• Why do we assign the part of speech of the first word in the paragraph to
A before the start of the iteration? In the first step of the iteration, we are
looking at the second row of the table. At this stage, we wish to know if the
previous word (first word in this case) is an adjective or not. This is the reason
we make this assignment.

• Why do we assign the part of speech of the current word to A just before the
end the while loop? This is done so that the variable A can store the part of
speech of the previous word in the next step of the iteration.

Page 4
3. (2 points) We have a non-empty list called authList that stores the names of all authors
in the “Library” table sorted in alphabetical order of author names. There is one element
corresponding to each book in the table. This results in many duplicates. The following
procedure attempts to extract the unique list of authors, while preserving the sorted
order. The pseudocode may have mistakes. Identify all such mistakes (if any). It is a
Multiple Select Question (MSQ).

1 uniqueList = [ ]
2 uniqueList = uniqueList ++ first(authList)
3 prev = first(authList)
4 foreach x in rest(authList) {
5 if (x == prev) {
6 uniqueList = uniqueList ++ [x]
7 }
8 prev = x
9 }

 Error in line 1

Error in line 2
 Error in line 3

Error in line 5
 Error in line 8
 No error

Solution: A good approach for problems of this kind is to quickly go through the
entire code once and get an overall understanding of it. We can then pause at each
line and see if it has any errors.
In the first line, uniqueList is initialized to an empty list. The name of the vari-
able is very suggestive. This is probably going to be the list that stores the list of
unique authors. Going down, we see that we are looping through all the elements
in rest(authList) and adding elements to uniqueList whenever some condition is
satisfied.
Let us go line by line. There is no error in line 1. In line 2, the intention is to add
the first element in authList to uniqueList. There is an error in the way it is done.
Only two lists can be combined with the “++” operation, whereas a list and a string
are being combined here. The correct code is as follows:
uniqueList = uniqueList ++ [first(authList)]

Page 5
There is no obvious error in the next line. The variable prev is storing the first ele-
ment in the list authList. Again, the variable naming is suggestive. prev probably
stands for previous. So, the prev is in all likelihood storing the previous element.
There is no error in line 4. That is clear from the options. We are iterating through all
elements in authList except the first. This is because of the term rest(authList).
Inside the foreach loop, we have an if-condition. This if-condition is checking if the
previous element is equal to the current element. If they are equal, then this element
is added to uniqeList.
We know that authList is a list of author names sorted in alphabetical order of
author names. If there are duplicates, then they will appear as adjacent elements in
the list. For example, consider the following sorted list:
[“Kalam”, “Kalam”, “Narayan”, “Roy”, “Roy”]
According to the current version of the code, whenever the previous name matches
the current name, we are adding it to uniqueList. This is exactly the behavior that
we don’t want to see. Note that we start by adding the first element in authList to
uniqueList. From then on, we only add the current element if it is not the same as
the previous element. Therefore, there is an error in line number 6. The corrected
version should be as follows:
if (x 6= prev)
Finally, in line 8, the variable prev is being updated to the current author name.
There is no error in this line. This assignment statement is similar to the one that we
saw in the previous question. This is done so that in the next step of the iteration,
the variable prev will store the previous element in the list.

Page 6
4. (3 points) The procedure visitedShop returns the list of names of people who have
visited a particular shop in the “Shopping Bills” dataset. It accepts the shop’s name
as a parameter. Additionally, each customer must be represented exactly once in the
returned list. The following pseudocode may have mistakes. Identify all such mistakes
(if any). It is a Multiple Select Question (MSQ).

1 Procedure visitedShop(shop)
2 S = “None”
3 while (Pile 1 has more cards) {
4 Read the top card X from Pile 1
5 if (X.ShopName == shop) {
6 if (not(member(S, X.CustomerName))) {
7 S = S ++ [X.ShopName]
8 }
9 }
10 Move X to Pile 2
11 }
12 return (S)
13 End visitedShop

14 Procedure member(L, name)


15 present = True
16 foreach x in L {
17 if (x == name) {
18 present = True
19 exitloop
20 }
21 }
22 return (present)
23 End member

Page 7

Error in line 2
 Error in line 6

Error in line 7

Error in line 15
 Error in line 17
 Error in line 18
 No error

Solution: First, a quick look at the code. The while loop in the procedure visited-
Shop goes through all cards in the “Shopping bills” dataset. Inside, there is a nested
if-block. The outer if-condition checks if the shop name of the current card matches
the input parameter. If it is true, then the inner if-condition checks for some other
condition that involves the procedure member. If this condition evaluates to True,
we go ahead and add the shop name to S.
Let us now look at the procedure member. This procedure should be familiar as
we have already seen it in the lectures and tutorials. It accepts two parameters. The
first parameter is a list L and the second parameter is some variable called name.
It is supposed to return True if the element name is in the list and False otherwise.
With this background, let us go through the code line by line. In line 2, we see that
S has been initialized to “None”. This is an error. This is because S is the variable
that is being returned by visitedShop and this procedure is supposed to return a
list. The correct version of line 2 should be:
S=[]
Lines 3 and 4 are error free. Line 5 doesn’t have any error either. This procedure is
concerned with those people who have visited a particular shop. So, the if-condition
in line-5 is checking for exactly that.
Line 6 is a bit involved. So, let us unpack it. member(S, X.CustomerName)
returns the value True if the customer’s name is present in the list. This means that
not(member(S, X.CustomerName)) returns False if the customer is present in the
list. For now, let us suspend our judgement regarding line 6 and move on.
In line 7, we are adding the shop name to the list if the customer’s name is not
present in the list. Let us go back to the question statement and see if this is what
we expect. We wish to find the list of names of people who have visited the shop. But,
if someone has visited it multiple times, then we want only one entry corresponding
to this person in the list S. This is the reason we are checking if X.CustomerName is
present in the list. We should add a name only if it is not already present in S. In
other words, only if not(member(S, X.CustomerName)) evaluates to True.

Page 8
However, there is a subtle error in line 7. Instead of appending the customer’s name
to the list, we are appending the shop’s name. So the correct version of line 7 is:
S = S ++ [X.CustomerName]
There are no more errors in the procedure visitedShop. That leaves us with the
procedure member. Line 15 looks wrong. Initially, we don’t know if name is
present in the list or not. So, it is best to initialize present to False. Let us go
through the remaining code to see if this is indeed an error.
Line 16 looks fine. In line 17, we see that if name is already present in the list L,
we set the variable present to True and then exit the loop. This is the expected
behavior, which means that there is nothing wrong with lines 16-21.
In line 22, we return present. No error there as well. Now we go back to line 15. It
becomes clear that there is an error in this line. present should be False to begin
with. If, we find name in the list L, then we update present to True, if not we let
it remain as it is.
In summary, lines 2, 7 and 15 have errors in them.

Page 9
5. (4 = 2 + 2 points) The following pseudocode is executed on the “Words” table. Assume
that the rows in the table are sorted in the ascending order of sequence number.

start = True
outList = [ ]
while (Table 1 has more rows) {
Read the first row X in Table 1
if (start) {
inList = [ ]
start = False
}
inList = inList ++ [ [X.Word, X.PartOfSpeech] ]
if (X.Word ends with a full stop) {
outList = outList ++ [inList]
start = True
}
Move X to Table 2
}

(a) At the end of execution, which of the following statements are true about the
variable outList? It is a Multiple Select Question (MSQ).

Each element in outList corresponds to one sentence from the paragraph.
 Each element in outList corresponds to one word from the paragraph.
 Each element in outList corresponds to one character from the para-
graph.

outList is a list of lists.

Solution: Consider the first if-condition inside the while loop. In the first step
of the iteration, the variable start is already True. So, the if-block is executed.
Coming out of this if-block, start holds the value False and inList is initialized
to an empty list.
Moving on, the current word (in this case, the first word) and its part of speech
are added as an element to inList. Note that this element is itself a list con-
sisting of two elements. inList will now look like this:
[ [“It”, “Preposition”] ]
As the word doesn’t end with a full stop, the second if-block is not executed. In
the next step of the iteration, start is False, so the first if-block is not executed.

Page 10
The second word and its part of speech are now added to the list inList. So,
inList now looks as follows:
[ [“It”, “Preposition”], [“was”, “Verb”] ]
As this word also doesn’t end with a full stop, we move on to the next step. We
keep doing this until we reach a word that ends with a full stop. At this point,
the second if-block is executed. Here, the list inList is added to outList and
the variable start is set to True. So, the first element of outList is a list and
corresponds to the first sentence in the paragraph.
At the next step, the first if-block is going to get executed because the current
value of the variable start is True. After coming out of this if-block, inList is
again empty and start holds the value False.
The pattern would have become clear by now. inList will start holding the
contents of the second sentence. Once we reach the end of the second sentence,
inList will be added to outList.
So, each element of outList corresponds to one sentence form the paragraph.
Each element of outList is itself a list. This means that outList is a list of
lists.

(b) Which of the following statements are true about the variable start during the
course of the execution of the above pseudocode? It is a Multiple Select Question
(MSQ).
 The variable start is set to False at the last word of every sentence.

The variable start is set to True at the last word of every sentence.

The variable start is set to False at the first word of every sentence.
 The variable start is set to True at the first word of every sentence.

Solution:
start is set to True to begin with. After seeing the first word of the paragraph,
which also happens to be the first word of the first sentence, start is set to
False. Every time we come to the last word of a sentence, start is set to True.
The next step of the iteration is nothing but the first word of the next sentence.
After processing this, start is again set to False. From this it becomes clear
that start is set to True at the last word of every sentence and is set to False
at the first word of every sentence.

Page 11
6. (7 = 2 + 2 + 3 points) We take the variable outList obtained at the end of execution
of the pseudocode in the previous question. Now, we execute the following pseudocode.

someVar = 0, count = 0, i = 0
foreach x in outList {
someVar = someVar + length(x)
foreach y in x {
if (last(y) == “Noun”) {
count = count + 1
}
}
i=i+1
}

(a) What does the variable count store at the end of execution?

It is the number of nouns in the paragraph.
It is the number of nouns in the first sentence of the paragraph.
It is the number of sentences in the paragraph that begin with a noun.
None of the above.

Solution: We have a nested iteration. The outer loop goes through each ele-
ment x in outList. x corresponds to a sentence in the paragraph. Each element
y in x corresponds to a word in the sentence. y itself is a list of two elements,
whose first element is the word and last element is its part of speech.
The inner loop iterates through the list x. The if-condition inside the inner loop
is checking if a word is a noun. Note that y itself is a list, whose last (second
in this case) element is the part of speech of the word. So, count stores the
number of nouns in the paragraph.

Page 12
(b) What does the variable someVar store at the end of execution?

It is the number of words in the paragraph.
It is the number of sentences in the paragraph.
It is the number of characters in the paragraph.
None of the above.

Solution:
x corresponds to a sentence. length(x) is nothing but the number of words
in the sentence represented by x. So, someVar is the sum of the number of
words across all sentences. Therefore, it will represent the number of words in
the paragraph.

(c) Which of the following statements are true about the variable i at the end of exe-
cution? It is a Multiple Select Question.
 It is the number of words in the paragraph.

It is the number of sentences in the paragraph.

It is equal to the number of elements in outList
 It is equal to the number of elements in inList

It is equal to length(outList)
 It is the number of characters in the paragraph.

Solution: i gets incremented every time we go through a sentence x in the


pargraph. So, at the end of execution, i will store the number of sentences in
the paragraph. This is the same as the number of elements in the list outList,
which is the same as length(outList).

Page 13
7. (4 = 2 + 2 points) stations is a list that contains the sequence of stations visited by a
train from the “Trains” dataset. Each element in stations is a list: [Name, Distance],
the first entry is the name of the station, while the second entry is the distance of this
station from the first station in the list.
minDist is a procedure that accepts stations as a parameter and returns the names
of a pair of consecutive stations which have the shortest distance between them on this
route. Complete the following procedure.

Procedure minDist(stations)
pair = [“None”, “None”]
min = 10000
prev = first(stations)
foreach x in rest(stations) {
diff = last(x) - last(prev)
*************************
* Fill the code *
*************************
prev = x
}
return (pair)
End minDist

(a) There may be multiple pairs having the same minimum distance. If we wish to find
a pair of stations closest to the first station in the list, which of the following is the
correct code fragment?

if (diff < min) {
min = diff
pair = [first(prev), first(x)]
}

 if (diff ≤ min) {
min = diff
pair = [first(prev), first(x)]
}

Page 14
 if (diff < min) {
min = diff
pair = [last(prev), last(x)]
}

 if (diff ≤ min) {
min = diff
pair = [last(prev), last(x)]
}

Solution:
pair is the list returned by this procedure. It is initialized to [“None”, “None”]
as it will be storing the names of two stations, both of which are strings. As we
are finding the minimum distance, min is initialized to 10000. In the context
of distances between stations, 10000 is a very high value. So this initialization
is reasonable.
Similar to the questions that we have seen before, we have a variable prev that
stores the information of the previous element in the list. We initialize it with
the first element in the list and start the iteration from the second element.
Now, we loop through each station in rest(stations). The variable diff captures
the distance between the previous station and the current station. The code
that we need to complete should update the variable min and pair whenever
we come across a pair of stations that have a shorter distance between them
than the current minimum.
The correct code fragment is as follows:
if (diff < min) {
min = diff
pair = [first(prev), first(x)]
}
We will try to understand why this is correct. Let us see what happens if
there are a pair of stations that have the same minimum distance. Consider the
following example:
[ [“stn-1”, 100], [“stn-2”, 120], · · · , [“stn-7”, 1000], [“stn-8”, 1020], · · · ]
Assume that the minimum distance is 20 and there are two pairs of stations
having this distance:
[“stn-1”, “stn-2”] and [“stn-7”, “stn-8”]
Our code is supposed to return [“stn-1”, “stn-2”] as this is the pair that is closest
to the first station on the list. After processing the element [“stn-2”, 120] in
the loop, diff will hold the value 20, min would be set to 20 and pair will be
[“stn-1”, “stn-2”]. When we come to the element [“stn-8”, 1020], diff will again
be 20. Now look at the if-condition:

Page 15
if (diff < min)
Note that we don’t want pair to be updated at this stage. This behavior is
guaranteed only if the symbol is <. Had it been ≤, pair would have been
updated with the value [“stn-7”, “stn-8”]. This is because 20 ≤ 20 will evaluate
to true.

(b) There may be multiple pairs having the same minimum distance. If we wish to find
a pair of stations closest to the last station in the list, which of the following is the
correct code fragment?
 if (diff < min) {
min = diff
pair = [first(prev), first(x)]
}

if (diff ≤ min) {
min = diff
pair = [first(prev), first(x)]
}

 if (diff < min) {


min = diff
pair = [last(prev), last(x)]
}

 if (diff ≤ min) {
min = diff
pair = [last(prev), last(x)]
}

Solution:
The only difference here is that the if-condition should have the ≤ symbol:
if (diff ≤ min)
This way, the pair of stations that is closest to the last element in the list
stations will be updated. To summarize, if you have (diff < min), then the first
occurrence of minimum will be stored in pair and all subsequent occurrences
with the same minimum will be ignored. If you have (diff ≤ min), every time
the same minimum value occurs, pair will be updated, so that when we exit
the loop, the last such occurrence will be recorded in pair.

Page 16
8. (4 points) stns is a list that contains information about the sequence of stations visited
by a train. Specifically, each element in this list is itself a list: [Arrival, Departure].
The first element in stns corresponds to the starting station for the train and the last
element corresponds to the ending station for the train.
waitTime(arr, dep) is a procedure that accepts the arrival time and departure time
of a train at a given station as input and returns the waiting time at that station in
minutes.
We wish to find the average waiting time across all intermediate stations where the train
stops and store this result in variable avg. The pseudocode may have mistakes. Identify
all such mistakes (if any). It is a Multiple Select Question (MSQ).

1 total = 0, count = 0, avg = 0


2 foreach x in init(rest(stns)) {
3 total = total + waitTime(first(x), last(x))
4 count = count + 1
5 }
6 if (count 6= 0) {
7 avg = total / count
8 }

 Error in line 2
 Error in line 3
 Error in line 4
 Error in line 6
 Error in line 7

No error

Solution:
As this is a small piece of code, let us go through it line by line. Line 1 seems to be
harmless. Line 2 looks quite complicated and needs some unpacking. Let us do it
with an example. Consider the following list
stns = [ [“None”, “10:50”], [“3:20”, “3:35”], [“6:00”, “6:02”], [“8:00”, “None”] ]
The interesting observation about this list is that the first and last stations do not
have any waiting time. This is because, the train is starting at the first station, and
there is no arrival time for the first element. As the train arrives at the last station
and completes its journey, there is no departure time for the last element in the list.

Page 17
This means that we are interested in only the intermediate stations in the list, ex-
cluding the first and the last elements. Is there a way to do this? Yes, the procedures
rest and init come to our rescue. To get all elements other than the first, we use:
rest(stns)
In the case of our example, this would give the following result:
[ [“3:20”, “3:35”], [“6:00”, “6:02”], [“8:00”, “None”] ]
Now, to get all elements except the last element, we take the init of the list given
above:
init(rest(stns))
This results in:
[ [“3:20”, “3:35”], [“6:00”, “6:02”] ]
Now, going back to the pseudocode, we see that there is nothing wrong with line
2. In lines 3 and 4, we are merely accumulating the total waiting time in total and
counting the number of intermediate stations using count. So no problems in the
foreach code-block.
Getting out, we check if count is non-zero. If true, we go ahead and compute the
average. Again, no errors. But why is this check necessary? Consider a train which
doesn’t stop at any intermediate station. Its list would look like this:
stns = [ [“None”, “3:35”], [“6:00”, “None”] ]
In this case, the foreach block would not be executed as init(rest(stns)) is an empty
list. Why? This is because there are only two elements, the first and the last, both
of which are ignored. Therefore, count and avg will be zero. This the reason we
need to have a check if count is zero or not at line 6.
To summarize, this pseudocode has no errors!

Page 18
9. (8 = 2 + 2 + 4 points) trains is a list that contains information about trains associ-
ated with a station stn. Specifically, each element in this list is another list: [Arrival,
Departure]. If the arrival or departure time is empty, it is represented as “None”.

flag1 = False, flag2 = True


count = 0
foreach x in trains {
if (first(x) == “None” or last(x) == “None”) {
flag1 = True
}
else {
count = count + 1
}
}
if (count == length(trains)) {
flag2 = False
}

(a) Which of the following statements about the variable flag1 is true at the end of
execution of the above pseudocode?

It is True if and only if stn is a starting or ending station for at least one
train in the list
It is False if and only if stn is a starting or ending station for at least one
train in the list
It is True if and only if stn is a stating station for one train and ending
station for some other train in the list
It is False if and only if stn is a starting station for one train and ending
station for some other train in the list

Solution: flag1 is False to begin with. Then, we iterate through all the trains
in the list trains. The only place where flag1 is updated is inside the if-block
within the foreach loop. Let us take a closer look at the if-condition:
fist(x) == “None” or last(x) == “None”
flag1 will be updated to True if one of the two conditions evaluates to true. For
the sake of argument, let first(x) be “None”. What does this mean? first(x)
is the arrival time of some train at stn. If this arrival time is “None”, it means
that stn is the starting station for this train. Since this train is starting from
this station, it only has a departure time and no arrival time.

Page 19
Likewise, if last(x) is “None”, then stn is the ending station for this train.
flag1 is set to true whenever one of these two conditions evaluates to true:

• stn is the starting station for a train

• stn is the ending station for a train

Therefore, at the end of execution, flag1 is true if and only if stn is a starting
station or ending station for at least one train in the list.

(b) What does the variable count represent at the end of execution of the above pseu-
docode?
It is number of trains associated with stn.
It is the number of trains for which stn is a starting station.
It is the number of trains for which stn is an ending station.

It is the number of trains for which stn is neither a starting nor an ending
station.

Solution: count is incremented inside the else-block. We enter the else-block


only if both the conditions inside the if-block evaluate to False. That is, first(x)
is not “None” and last(x) is not “None”. This means, for the train correspond-
ing to x, stn is neither a starting station nor an ending station. It is only
an intermediate station where it stops. Therefore, count stores the number of
trains for which stn is neither a starting nor an ending station.

Page 20
(c) At the end of execution of the code given above, what can be said about the values
stored by the boolean variables flag1 and flag2?

flag1 and flag2 always store the same value.
flag1 and flag2 always store opposite values.
flag1 always stores the value True.
flag2 always stores the value True.
There is no relationship between these two variables.

Solution:
flag2 is set to True to begin with. It is updated if the last if-condition evaluates
to True. When does that happen? It happens if count is equal to the number
of elements in trains. We already know that count is storing the number of
trains in the list for which stn is neither a starting nor an ending station. If
count is equal to length(trains), then for every train in the list, stn is neither
a starting nor ending station. This means that stn is only an intermediate
station for all trains in the list.
So, flag2 becomes False if there is no train in the list for which stn is a starting
or ending station. Consequently, flag2 is True if there is at least one train in
the list for which stn is a starting or ending station. But this is exactly the case
with flag1!
Therefore, flag1 and flag2 always store the same value at the end of execution!

Page 21
Computational Thinking
Week - 6
Graded Assignment Solution
1. The following pseudocode is executed using the “Scores” table. What will the values of
A and B represent at the end of execution? [3 Marks]

D={}
while (Table 1 has more rows) {
Read the first row X in Table 1
if (isKey(D, X.CityTown)) {
if (D[X.CityTown] > X.Mathematics) {
D[X.CityTown] = X.Mathematics
}
}
else {
D[X.CityTown] = X.Mathematics
}
Move X to Table 2
}
A = 0, B = 100
foreach Y in keys(D) {
if (B == D[Y]) {
A=A+1
}
if (B > D[Y]) {
A=1
B = D[Y]
}
}

a. A = Cities where students score the highest marks in Mathematics


B = The highest marks in Mathematics
b. A = Number of cities where students score the highest marks in Mathematics
B = The highest marks in Mathematics
c. A = Number of cities where students score the lowest marks in Mathematics
B = The lowest marks in Mathematics
d. A = Always more than one
B = The highest marks in Mathematics
Computational thinking Week - 6 Graded Assignment Solution Page 2 of ??

Solution: D is initialized as an empty dictionary. The scores table is iterated using the
iterator X. In each iteration, the if-condition check whether the X.CityTown is a key in D.
If the condition evaluates to true, then another if-condition (nested inside) checks whether
the Mathematics marks of X less than D[X.CityTown]. If the condition evaluates to true,
then value D[X.CityTown] is replaced by X.Mathematics. More precisely, D[X.CityTown] is
updated by a new value if X.Mathematics is lesser than it. Then, D[X.CityTown] stores the
lowest mathematics mark of students from X.CityTown. There is no else-block for the nested
(inner) if-block. Then we come out of the outer if-block.
The else-part of the outer if-block is executed when X.CityTown is not a key of D. Here, we
create a key X.CityTown in D, and initialize the value for the key as X.Mathematics. At the
end of the while-block, D captures the following information: For each CityTown C, D[C] is
the lowest Mathematics marks of the students from the city C.
Variables A and B are initialized with the value zero. The keys of D are iterated using the
iterator Y. In each iteration, The first if-condition checks whether B and D[Y] are same. If the
condition evaluates to true, then the value of A is incremented by one. The second if-condition
checks B > D[Y]. If the condition evaluates to true, then A is set to one and B is set to
D[Y]. Based on the usage of variables, A is used as a counter variable and Bis used to store
some value and it is updated when there is a smaller value than B is assigned for a key in D.
Therefore, whenever a key Y is encountered with B > D[Y], B is updated to D[Y], and A is
set to one. Whenever a key encountered with B == D[Y], the value of A is incremented by
one.
Thus, B captures the lowest value among the values in D, and A captures the number of
occurrence of the lowest value. Since D captures the lowest mathematics marks of each city,
A and B capture the following information:
A = Number of cities where students score the lowest marks in Mathematics
B = The lowest marks in Mathematics
Computational thinking Week - 6 Graded Assignment Solution Page 3 of ??

2. The following pseudocode is executed using the “Scores” table. What will the value of
B represent at the end of execution? [4 Marks]

D={}
while (Table 1 has more rows) {
Read the first row X in Table 1
D = updateDictByField(D, X.Physics)
Move X to Table 2
}
B = findAKey(D)

Procedure updateDictByField(D, Value)


if (isKey(D, Value)) {
D[Value] = D[Value] + 1
}
else {
D[Value] = 1
}
return (D)
End updateDictByField

Procedure findAKey(D) {
Key = -1, Value = 0
foreach A in keys(D) {
if (D[A] > Value) {
Value = D[A]
Key = A
}
}
return (Key)
End findAKey

a. Number of repeated marks in Physics


b. Minimum marks in Physics
c. Maximum marks in Physics
d. Most frequent marks in Physics
Computational thinking Week - 6 Graded Assignment Solution Page 4 of ??

Solution: First we loot at the procedure updateDictByField. The parameters passed to


the procedure are a dictionary and a value. The if-condition checks whether the Value is a
key of D. If the condition evaluates to true, then the value of D[Value] is incremented by
one. Otherwise, D[Value] is initialized with value one. Overal, the procedure updates the
dictionary Das follows: if Value is not a key then create it as a key of Dand initialize with a
value one, otherwise increment the value of D[Value] by one.
Now, we look at the procedure findAKey. Given a parameter D, the procedure computes
the following: Two variables Key and Value are initialized with values -1 and 0. The keys of
D are iterated using the iterator A. During the iteration, Key captures the key which holds
the maximum value assigned in D, and Value captures the maximum value. At the end of
the procedure, Key is returned.
In the main pseudocode, D is initialized as an empty dictionary. The scores table is iterated
using an iterator X. In each step of iteration, the procedure updateDictByField is called
with the parameters D and X.Physics. At the end of the iteration, the keys of D are the
Physics marks scored by the students, and the values are the number of times each marks are
scored by the students. The procedure findAKey is called with the parameter D. It returns
the key which assigned with a maximum value. Since the keys of D are the Physics marks, the
returned value from the procedure is the Physics marks which is scored by maximum number
of people. Therefore, B captures the following information: Most frequent marks in Physics.
Computational thinking Week - 6 Graded Assignment Solution Page 5 of ??

3. The following pseudocode is executed using the “Scores” table. What will be the value of B at
the end of execution? [6 Marks]

D = {“Mathematics”: { }, “Physics”: { }, “Chemistry”: { }}, B = 0


while (Table 1 has more rows) {
Read the first row X in Table 1
D = updateDictByField(D, X, “Mathematics”)
D = updateDictByField(D, X, “Physics”)
D = updateDictByField(D, X, “Chemistry”)
Move X to Table 2
}
while (Table 2 has more rows) {
Read the first row X in Table 2
if (eligible(D, X) > 1) {
B=B+1
}
Move X to Table 1
}

Procedure updateDictByField(D, Y, Subject)


if (isKey(D[Subject], Y.CityTown)) {
if (D[Subject][Y.CityTown] < Y.Subject) {
D[Subject][Y.CityTown] = Y.Subject
}
}
else {
D[Subject][Y.CityTown] = Y.Subject
}
return (D)
End updateDictByField

Procedure eligible(D, X) {
SubList = [“Mathematics”, “Physics”, “Chemistry”], C = 0
foreach Subject in SubList{
if (D[Subject][X.CityTown] == X.Subject) {
C=C+1
}
}
return (C)
End eligible

Ans: 10
Computational thinking Week - 6 Graded Assignment Solution Page 6 of ??

Solution: The procedure updateDictByField receives a dictionary D, a row Y and a subject


Subject as parameters. First, we check whether Y.CityTown is a key in D[Subject]. If it
evaluates to true, then we update the value of the key Y.CityTown as Y.Subject when existing
value of the key is less than Y.Subject. That is, D captures the maximum marks of a student
in the subject Subject in each city.
The maximum subject marks of the students from each city is given in the following table.

CityTown Mathematics Physics Chemistry


Ambur 81 82 87
Bangalore 97 92 92
Chennai 87 92 92
Erode 72 92 97
Madurai 87 83 89
Nagercoil 62 62 57
Salem 62 45 91
Theni 76 58 90
Trichy 89 86 93
Vellore 93 92 91

The procedure eligible receives the dictionary D and a student row X as parameters. For each
subject, we check whether the student is city topper in the subject where the maximum marks
of the subject in the city is stored in the dictionary D. Therefore, C captures the number of
subjects in which X is a city topper in the subject. The value of C for the student information
in the “Scores” table can be tabulated as follows.
Computational thinking Week - 6 Graded Assignment Solution Page 7 of ??

CardNo CityTown Mathematics Physics Chemistry C


6 Ambur 81 82 87 3
11 Bengaluru 97 92 92 3
23 Bengaluru 97 91 88 1
21 Bengaluru 78 69 74 0
9 Bengaluru 63 88 73 0
8 Bengaluru 74 64 51 0
25 Chennai 87 75 92 2
5 Chennai 71 92 84 1
26 Chennai 74 71 82 0
3 Chennai 42 53 78 0
2 Chennai 57 54 77 0
12 Chennai 52 64 71 0
10 Chennai 64 72 68 0
17 Chennai 62 81 67 0
18 Erode 72 92 97 3
0 Erode 68 64 78 0
13 Madurai 65 73 89 1
4 Madurai 87 64 89 2
28 Madurai 74 83 83 1
24 Madurai 44 72 58 0
27 Madurai 81 76 52 0
22 Nagercoil 62 62 57 3
1 Salem 62 45 91 3
15 Theni 76 58 90 3
14 Trichy 89 62 93 2
19 Trichy 56 78 62 0
16 Trichy 87 86 43 1
20 Vellore 93 68 91 2
29 Vellore 72 66 81 0
7 Vellore 84 92 76 1

In the main pseudocode, we check the number of students who are city toppers in more than
one subject. That is, the number rows in the above table with C value more than one.
Computational thinking Week - 6 Graded Assignment Solution Page 8 of ??

4. The following pseudocode is executed using the “Shopping Bills” dataset. At the end of the
execution, the variable D captures the following information: for each customer Z, D[Z][“Shop”]
stores the shops visited by Z, and D[Z][“Category”] stores the categories of the items purchased
by Z. But the pseudocode may have mistakes. Identify all such mistakes (if any). It is a
Multiple Select Question (MSQ). [5 marks]

1 D={}
2 while (Pile 1 has more cards) {
3 Read the top card X in Pile 1
4 D = updateDictionary(D, X)
5 Move X to Pile 2
6 }

7 Procedure updateDictionary(D, Y)
8 if (not isKey(D, Y.CustomerName)) {
9 D[Y.CustomerName] = { “Shop”: [ ], “Category”: [ ]}
10 }
11 D[Y.CustomerName][“Shop”][Y.ShopName] = True
12 foreach A in Y.ItemList {
13 D[Y.CustomerName][“Shop”][A.Category] = True
14 }
15 return (D)
16 End updateDictionary

a. Error in Line 1
b. Error in Line 9
c. Error in Line 12
d. Error in Line 13
e. Error in Line 15
Computational thinking Week - 6 Graded Assignment Solution Page 9 of ??

Solution: The objective of the pseudocode is to find the following: for each customer Z, find
the shops visited by Z, and the item categories which are bought by C. In the pseudocode,
D is used to store the above information. For each customer Z, D[Z] is a dictionary with keys
“Shop” and “Category”. D[Z][“Shop”] stores the shops that are visited by Zand D[Z][“Category”]
stores the categories of the items purchased by Z. So, D[Z][“Shop”] is a dictionary that assigns
true value for all shop visited by Z. Similarly, D[Z][“Category”] is also a dictionary.
The first step is to read the cards and generate the dictionary D. Line 1 - 6 perform the reading
and invoke the procedure updateDictionary. Clearly, the pseudocode has no error in this
part.
Let us look at the procedure updateDictionary. Here we have to update the dictionary fields
for the key Y.CustomerName. The first step is to check whether Y.CustomerName is a key in
D. If it is not a key, then create X.CustomerName as a key. The value for the key is defined
as follows:
D[Y.CustomerName] = { “Shop”: { }, “Category”: { }}
In Line 9, the keys are assigned to empty lists. This is a mistake in the pseudocode. Therefore,

Error in Line 9.

Note that the keys are assigned to empty dictionaries since we encounter the customer for the
first time. If the customer name is exists in the keys list, then we move to the next step. Next
we have to add the shop name to the dictionary. This is done in Line 11. Note that the shop
name is already exists in the dictionary, then it overwrite the true assignment. It will not harm
the objective in any aspect. Finally, we check the item categories. Iterate the item list of the
bill using the iterator A. Add the item category to the dictionary in the field “Category” as
follows:
D[Y.CustomerName][“Category”][A.Category] = True
In Line 13, the item category is added to the key “Shop”. Therefore,

Error in Line 13.

At the end of the procedure, the updated dictionary D is returned.


Computational thinking Week - 6 Graded Assignment Solution Page 10 of ??

5. The following pseudocode is executed using the “station wise” cards of the “Train” dataset.
At the end of the execution, STN captures the following information: for a station X, and a
day of a week A, STN[X][A] stores the number of trains running through X on the day A.
Choose the correct code fragment to complete the pseudocode. [Note: Assume that for each
station, the train list is given in a single card.] [4 Marks]

STN = { }
while (Pile 1 has more cards) {
Read the top card X in Pile 1
STN[X.StationName] = getInfo(STN, X)
Move X to Pile 2
}

Procedure getInfo(STN, X)
*********************
* Fill the code *
*********************
return (D)
End getInfo

a.
D={}
foreach A in X.TrainList {
foreach B in A.Days {
D[B] = 1
}
}
b.
D = { “M”: 0, “Tu”: 0, “W”: 0, “Th”: 0, “F”: 0, “Sa”: 0, “Su”: 0}
foreach A in X.TrainList {
foreach B in A.Days {
D[B] = 1
}
}
c.
D={}
foreach A in X.TrainList {
foreach B in A.Days {
D[B] = D[B] + 1
}
}
d.
Computational thinking Week - 6 Graded Assignment Solution Page 11 of ??

D = { “M”: 0, “Tu”: 0, “W”: 0, “Th”: 0, “F”: 0, “Sa”: 0, “Su”: 0}


foreach A in X.TrainList {
foreach B in A.Days {
D[B] = D[B] + 1
}
}
Computational thinking Week - 6 Graded Assignment Solution Page 12 of ??

Solution: The dictionary STN captures the following information. For each station X, and
for each day of a week A, STN[X][A] is an integer that represents the number of trains are
running through X on the day A. First we have to understand the structure of D. First of
all, D is a dictionary where stations are the keys. For each station X, STN[X] is another
dictionary where days of a week are the keys.
In the pseudocode, the cards are iterated using the iterator X. In each step of the iteration,
STN[X.StationName] is obtained from the procedure getInfo.
Now we look at the procedure getInfo. As we know that STN[X.StationName] is a dictionary,
the procedure getInfo should return a dictionary. Since it returns D, D should be a dictionary
which can be initialized as an empty dictionary.

D ={}

With this initialization of D, we need to create/initialize keys when they found for the first
time. If the key already exists, then we can update the keys. But, none of our answers are
checking the existence of any key in D. Therefore, D should be initialized with keys and initial
values for the keys.
We know that the keys of D are days of a week. Then, the keys of D is fixed and the values
are non-negative integers. Therefore, D can be initialized as follows:

D = { “M”: 0, “Tu”: 0, “W”: 0, “Th”: 0, “F”: 0, “Sa”: 0, “Su”: 0}

We assign the values are zero since no train is encountered for any day so far. Train list of the
station is iterated using the iterator A.

foreach A in X.TrainList

In each step of iteration, the running days of A is iterated using B.

foreach B in A.Days

For each day B, we have to increment one for D[B].

D[B] = D[B] + 1

By combining all the above codes, we get the following:

D = { “M”: 0, “Tu”: 0, “W”: 0, “Th”: 0, “F”: 0, “Sa”: 0, “Su”: 0}


foreach A in X.TrainList {
foreach B in A.Days {
D[B] = D[B] + 1
}
}
Computational thinking Week - 6 Graded Assignment Solution Page 13 of ??

6. The following pseudocode is executed using the “station wise” cards of the “Train” dataset.
Consider the dictionary STN computed in the previous question. Choose the correct statement(s)
from the options based on the pseudocode. [3 Marks]

Z={}
foreach A in keys(STN) {
C = 0, Y = 0
D = STN[A]
foreach B in keys(D) {
if (Y == D[B]) {
C=C+1
}
if (Y < D[B]) {
C=1
Y = D[B]
}
}
if (not isKey(Z, C)) {
Z[C] = 0
}
Z[C] = Z[C] + 1
}

a. Keys of the dictionary Z is integer


b. There can be a value C such that Z[C] is zero
c. All values of the dictionary elements are non-zero
d. The number of keys in Z is 8
Computational thinking Week - 6 Graded Assignment Solution Page 14 of ??

Solution: First, we understand the pseudocode. D is initialized as an empty dictionary.


keys(STN) is iterated using the iterator A. In each step of iteration, D stores STN[A]. We
know that STN[A] is a dictionary. In the subsequent foreach-block, we find the maximum
value assigned to any key and number of times the value appeared in D. These information
are stored in Y and C, respectively.
Once we computed C, we check whether C is a key in Z. Since C is an integer and Z[C] is
also assigned to an integer, both keys and values of Zare integers. Therefore,

Keys of the dictionary Z is integer.

Observe that the initial value of each key is set to zero. But in the next line, the value is
incremented by one. That is, for each key C, Z[C] is non-zero. Therefore,

All values of the dictionary elements are non-zero

C stores the maximum occurrence of the max value in dictionary D. Since keys of D are days
of a week, the maximum possible value of C is seven.
Computational thinking Week - 6 Graded Assignment Solution Page 15 of ??

7. Consider the dictionary STN computed in the previous question. Choose the correct pseudocode
to compute the number of stations which have trains passing through all days of a week. [4 Marks]

a.
Z=0
foreach A in keys(STN) {
foreach B in keys(STN[A]) {
if (STN[A][B] < 1) {
C = False
}
}
if (C) {
Z=Z+1
}
}
b.
Z=0
foreach A in keys(STN) {
C = True
foreach B in keys(STN[A]) {
if (STN[A][B] < 1) {
C = False
}
}
if (C) {
Z=Z+1
}
}
c.
Z=0
foreach A in keys(STN) {
C = True
foreach B in keys(STN[A]) {
if (STN[A][B] < 1) {
C = False
}
else {
C = True
}
}
if (C) {
Z=Z+1
}
}
Computational thinking Week - 6 Graded Assignment Solution Page 16 of ??

d.
Z=0
foreach A in keys(STN) {
C = False
foreach B in keys(STN[A]) {
if (STN[A][B] < 1) {
C = True
}
}
if (C) {
Z=Z+1
}
}
Computational thinking Week - 6 Graded Assignment Solution Page 17 of ??

Solution: For a station A and a day B, STN[A][B] denotes the number of trains passing
through the station A on the day B. We iterate the keys of STN using A, and keys of STN[A]
is iterated using B. The role of C is to capture that the station A is busy on all days. Then,
we should initialize C to True.
C = True
If we find a day in which no trains are passing through station A, then we have to set C to
False. That is,

if (STN[A][B] < 1) {
C = True
}

The variable Z should be incremented when C remains True at the end of the iteration over
the keys of STN[A].

if (C) {
Z=Z+1
}

Finally, by combining the pieces of code, we get the following pseudocode.

Z=0
foreach A in keys(STN) {
C = True
foreach B in keys(STN[A]) {
if (STN[A][B] < 1) {
C = False
}
}
if (C) {
Z=Z+1
}
}
Computational thinking Week - 6 Graded Assignment Solution Page 18 of ??

8. The following pseudocode is executed using the “Words” table. What will the value of
D represent at the end of the execution? [3 Marks]

D={}
while (Table 1 has more rows) {
Read the first row X in Table 1
D = updateDictionary(D, X)
Move X to Table 2
}

Procedure updateDictionary(D, Y)
i=1
while (i ≤ Y.LetterCount) {
B = ith letter in Y.Word
if (isKey(D, B)) {
D[B] = D[B] + 1
}
else{
D[B] = 1
}
i=i+1
}
return (D)
End updateDictionary

a. Frequency count of each alphabet in the table


b. Frequency count of each word in the table
c. Most frequent alphabet in the table
d. Frequency count of each alphabet in each part of speech
Computational thinking Week - 6 Graded Assignment Solution Page 19 of ??

Solution: First we consider the procedure updateDictionary. It receives a dictionary D


and a word Y as parameters. Based on the usage of D, keys of D are letters and values are
integers. We iterate the letters in the word Y using B. In the if-condition, we check whether
the letter B is a key in D. If it evaluates to true, then we increment the value of D[B] by one.
Otherwise, add B as a key to Dand initialize its value to one. Therefore, we add the number
of occurrence of each letter of Y to D.
In the main pseudocode, D is initialized as an empty dictionary. For each word X in the
table, D and X are passed to the procedure updateDictionary. Thus, the number of
occurrence of each letter in X is updated to the dictionary D. Therefore, D captures the
following information:

Frequency count of each letter in the table


Computational thinking Week - 6 Graded Assignment Solution Page 20 of ??

9. Consider the dictionary D and the procedure updateDictionary() in the previous question.
Let POS be a list that contains all part of speeches. Assume that given a dictionary D, there
exists a procedure max such that max(D) returns a list of keys which are mapped to the
maximum value. Choose the correct statement(s) from the options based on the following
pseudocode. [4 Marks]

C = {“Overall” : max(D)}
foreach A in POS {
Move all rows to Table 1
B={}
while (Table 1 has more rows) {
Read the first row X in Table 1
if (X.PartOfSpeech == A) {
B = updateDictionary(B, X)
}
Move X to Table 2
}
C[A] = max(B)
}

a. length(keys(C)) is same as the number of different part of speeches in the input dataset
b. C captures the list of most frequent alphabet occurred overall in the data set as well as
for each part of speech
c. C captures the most frequent alphabet occurred overall in the data set as well as for each
part of speech
d. length(keys(C)) is one more than the number of different part of speeches in the dataset
Computational thinking Week - 6 Graded Assignment Solution Page 21 of ??

Solution: The variable C is declared as a dictionary and initialized with a key “Overall” with
value as max(D) where max(D) is a list of keys which are assigned to the maximum value.
Therefore, max(D) is a list of letters with maximum number of occurrence. As it defined,
POS is a list of part of speeches. POS is iterated using A. In each iteration, all the rows of
“Words” table are moved to Table 1. Rows in the table 1 are iterated using X. For each row
X with part of speech as A, the dictionary D load the number of occurrence of the letters
in the word. That is, at the end of each iteration, B stores the frequency count of letter in
the words whose part of speech is A. max(B) will be stored as value for the key A in C. That is,

C captures the list of most frequent alphabet occurred overall in the data set as well as for
each part of speech.
At the end of the execution, C will have length(POS)+1 keys. Therefore,

length(keys(C)) is one more than the number of different part of speeches in the table.
Computational thinking Week - 6 Graded Assignment Solution Page 22 of ??

10. The following pseudocode is executed using the “Shopping bills” dataset. What will the value
of D represent at the end of the execution? [4 Marks]
D={}
while (Pile 1 has more cards) {
Read the top card X in Pile 1
D = updateDictionary(D, X)
Move X to Pile 2
}

Procedure updateDictionary(D, Y)
foreach A in Y.ItemList {
C = A.ItemName
if (isKey(D, C)) {
if (isKey(D[C], Y.ShopName)) {
if (D[C][Y.ShopName][“Price”] 6= A.Price) {
D[C][Y.ShopName][“Flag”] = True
}
}
else {
D[C][Y.ShopName] = { “Price”: A.Price, “Flag” : False}
}
}
else {
D[C] = { }
D[C][Y.ShopName] = { “Price”: A.Price, “Flag” : False}
}
}
return (D)
End updateDictionary

a. For an item C, and a shop S, D[C][S][“Flag”] is set to True if and only if the item is sold
for a constant price
b. For an item C, and a shop S, D[C][S][“Flag”] is set to True if and only if the item is
billed in more than one bill
c. For an item C, and a shop S, D[C][S][“Flag”] is set to True if and only if the item is sold
for variable price
d. For an item C, and a shop S, D[C][S][“Flag”] is set to True if and only if the item is
billed exactly one bill
Computational thinking Week - 6 Graded Assignment Solution Page 23 of ??

Solution: D is initialized as an empty dictionary. For each card X in the dataset, D is


updated by the procedure updateDictionary.
The procedure updateDictionary takes a dictionary and a card as parameters. For each
item C in the item list of Y, the if-condition checks whether C is a key in D. If the condition
evaluates to true, then check whether X.ShopName is a key in D[C]. If the condition evaluates
to true, then set the value for the key “Flag” to true when the value of the key “Price” is not
equal to A.Price. Therefore, in a shop S, for an item C, if C is sold for different prices in the
shop S, then D[C][S][“Flag”] is set to True.
For an item C, and a shop S, D[C][S][“Flag”] is set to True if and only if the item is sold for
variable price
Week-7, Graded
Week-7, Graded
Question-1 [2 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 2 [4 Marks]
Statement
Answer
Solution
Question 3 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 4 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question (5 - 7)
Statement
Question 5 [3 Marks]
Statement
(a)
(b)
(c)
(d)
Answer
Solution
Question 6 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 7 [4 Marks]
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question (8 - 9)
Statement
Explanation
Question 8 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Question 9 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Question 10 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution

Question-1 [2 Marks]
Statement
Let D be a non-empty dictionary. Choose the correct option(s). It is a Multiple Select Question
(MSQ).

Options
(a)

Let a be a key of dictionary D, then a is always an integer.


(b)

For keys a and b in D, if a != b then D[a] != D[b] is always True.

(c)

For keys a and b in D, a != b is always True.

(d)

Let D = { ‘a’: 5, ‘b’ : 4, ‘c’ : 6}, then the value of D[4] is 'b'.

Answer
(c)

Solution
a. Key of a dictionary is not necessary to an integer.

b. Two keys can have same values in a dictionary.

c. Keys of a dictionary are always distinct.

d. 4 is a value of key 'b', therefore, D['b'] will be 4 not D[4] will be 'b'.
Question 2 [4 Marks]
Statement
Let Z be a row in the "Words" table such that Z.Word = "reluctant". What will be the value of
alphaDict['t'] at the end of the execution of the following pseudocode? (NAT)

1 alphaDict = {'t':2, 'c':1, 'a':1, 's':0}


2 alphaDict = updateDict(Z, alphaDict)
3
4 Procedure updateDict(Z, Dict)
5 i = 1, x = 't'
6 while(i <= Z.LetterCount){
7 x = ith letter of Z.Word
8 if(not isKey(Dict, x)){
9 Dict[x] = 1
10 }
11 else{
12 Dict[x] = Dict[x] + 1
13 }
14 i = i + 1
15 }
16 return(Dict)
17 End updateDict

Answer
4

Solution
Procedure updateDict accepts two parameters as key, one row Z and other Dictionary D. It
returns an updated dictionary using the information in row Z.

Line 8 - line 10: If the letter x is not in the keys of D, store x in D as a key and map it to 1 (first time
seen.)

Line 11 - line 13: If the letter x is already a key of D (already seen before), then increment its value
by 1. Which means Dictionary D stores a letter as key mapped to the number of times it is seen
(frequency count of letter.)

In dictionary alphaDict, 't' is mapped to 2 before calling the procedure. The word "reluctant" has
two 't'. Due to line 12, 't' will be mapped to 4 (2 + 1 + 1). Therefore, alphaDict['t'] = 4.
Question 3 [3 Marks]
Statement
The following pseudocode is executed using the "Library" dataset. At the end of the execution, A
stores a dictionary with the author’s name as key mapped to the number of books written by
him/her. But the code may have mistakes. Identify all such mistakes (if any). Assume that all
statements not listed in the options below are free of errors. It is a Multiple Select Question
(MSQ).

1 A = {}
2 while(Table 1 has more rows){
3 Read the first row X from Table 1
4 if(isKey(A, X.Author)){
5 A[X.Author] = 1
6 }
7 else{
8 A[X.Author] = A[X.Author] + 1
9 }
10 Move X to Table 2
11 }

Options
(a)

Replacing the condition given in line 4 with the statement given below will provide the correct
result.

1 if(not isKey(A, X.Author))

(b)

Interchanging Line 4 and 7 will provide the correct result.

(c)

Interchanging Line 5 and 8 will provide the correct result.

(d)

The pseudocode will provide the correct result even without getting modified.

Answer
(a), (c)

Solution
At the end of the execution, A should store the author's name as key mapped to the number of
books written by them. The concept here would be that A should be initialized as an empty
dictionary first and then iterated through the rows of the table to update A.
Whenever a new author is found, the author name should be stored in the dictionary A as key
mapped to 1 (first book seen ever by the author).

But in Line 4: Opposite is being done. Therefore, to make the condition True in opposite situation
there should not. Therefore, option a is correct.

Once we find the author who is already in A, the value of author should be incremented and it is
being done properly by the else block.

As the condition in line 4 is opposite to what we want. We can swap line 5 with 8. This means, if
the author is already in A, then increment else initialize. Therefore, option c is also correct.
Question 4 [4 Marks]
Statement
The following pseudocode is executed using the "Library" Dataset. At the end of the execution,
firstBook stores a dictionary with the author's name as key mapped to the genre of their first
published book. But the code may have mistakes. Identify all such mistakes (if any). Assume that
all statements not listed in the options below are free of errors. Assume that the rows are
arranged in ascending order of publication years of the books. It is a Multiple Select Question
(MSQ).

1 firstBook = {}
2 while(Table 1 has more rows){
3 Read the first row X from Table 1
4 if(isKey(firstBook, X.Author)){
5 firstBook[X.Author] = X.Genre
6 }
7 Move X to Table 2
8 }

Options
(a)

Line 1: Incorrect initialization of firstBook

(b)

Line 4: Incorrect conditional statment

(c)

Line 7: There should always be an "else" block after "if" block

(d)

No mistakes

Answer
(b)

Solution
At the end of the execution, firstBook should store author's names as keys mapped to the genre
of their first book. The concept here would be:

Initialize firstBook as an empty dictionary


Go through each row of the Table 1
When a new author is being found, store author's name as key and map it to the genre
As we need the first book's genre only, we would not disturb this key
But the condition given in line 4, is just the opposite. It will even not work because the
condition in line 4 will never be True.
Therefore, the condition in line 4 should be if(not isKey(firstBook, X.Author)). Option b is
correct.
Any else block will not be required as there is no updating needed for a stored key.
Question (5 - 7)
Statement
Use the procedure doSomething given below for answering questions 5, 6, and 7.

1 Procedure doSomething(aList)
2 bDict = {}
3 bList = []
4 foreach a in aList{
5 if(not isKey(bDict, a)){
6 bDict[a] = True
7 bList = bList ++ [a]
8 }
9 }
10 return(bList)
11 End doSomething

Question 5 [3 Marks]
Statement
What will be the value of B at the end of the execution of the following pseudocode.

1 B = []
2 A = [3, 4, 5, 3, 1, 9, 4, 6, 5, 9]
3 B = doSomething(A)

(a)

[3, 4, 5, 1, 9, 4, 6, 5, 9]

(b)

[3, 4, 5, 1, 9, 6]

(c)

[1, 6]

(d)

[4, 1, 3, 4, 6, 5, 9]

Answer
(b)
Solution
Line 4: One element is being picked up from the list which is passed as parameter.

Line 5: If the element is not the key of dictionary bDict, i.e., the element is seen first time, then line
6 will be executed.

Line 6: The element is being stored in Dictionary and the same element is being appended to the
list bList.

Overall, An element of aList is being appended in bList if and only if it is seen first time. If an
element is repeated like 3, then the first time line 6 will be executed and then for rest 3, nothing
will happen.

Therefore, doSomething accepts a list as input and returns a list with the unique(distinct)
elements of input list.
Question 6 [4 Marks]
Statement
The following pseudocode is executed using the "Words" dataset and the procedure
doSomething mentioned above. What will sList store at the end of the execution.

1 sList = [], wList = []


2 while(Table 1 has more rows){
3 Read the first row X from Table 1
4 wList = wList ++ [X.Word]
5 if(X.Word ends with a full stop){
6 wList = doSomething(wList)
7 sList = sList ++ [wList]
8 wList = []
9 }
10 Move row X to Table 2
11 }

Options
(a)

List of words from the "Words" dataset.

(b)

List of unique words from the "Words" dataset.

(c)

List of lists of words of each sentence from the "Words" dataset.

(d)

List of lists of unique words of each sentence from the "Words" dataset

Answer
(d)

Solution
Line 4: wList stores the list of each word of dataset. But wList is being re-initialized to an empty list
in line 8. Line 8 is executed whenever full stop comes into the picture. Therefore, wList stores the
list of words of every sentence before it gets re-initialized.

Line 6: As wList is being updated with doSomething(wList). This procedure will return a list with
unique elements of wList. This means in line 6, wList is being updated with the list of unique
words of the current sentence.

Line 7: The current wList is being appended in sList, but wList is not being appended directly.
There is one square bracket with wList i.e., [wList], which means the list of the unique words of
the current sentence is being appended.
Therefore, sLists stores the list of lists of unique words of every sentence from the dataset.
Question 7 [4 Marks]
The following pseudocode is executed using the "Words" dataset and the procedure
doSomething mentioned above. Let explode(W) returns a list of characters of word W in the
same order as they are in the word. For example explode("thinking") returns ['t', 'h', 'i', 'n', 'k', 'i',
'n', 'g']. Ignore the punctuations like comma, full stop and so on. What will someList store at the
end of the execution.

1 W = [], someList = []
2 while(Table 1 has more rows){
3 Read the first row X from Table 1
4 W = explode(X.Word)
5 someList = someList ++ W
6 Move row X to Table 2
7 }
8
9 someList = doSomething(someList)

Options
(a)

List of alphabets from the "Words" dataset.

(b)

List of unique alphabets from the "Words" dataset.

(c)

List of lists of alphabets of each word from the "Words" dataset.

(d)

List of lists of unique alphabets of each word from the "Words" dataset

Answer
(b)

Solution
Line 4: W stores the list of alphabets of current word.

Line 5: W is being appended in someList. Which means someList stores the list of the alphabets
seen so for. As this whole process is being happened within the while loop, someList will store all
the list of of the alphabets seen so for till while loop gets ended.

Once the while loop gets ended, someList will be the list of all the alphabets present in the
dataset.

Line 9: The procedure doSomething is being called in the last. This returns the list of unique
elements. Therefore, someList will store the list of unique (distinct) alphabets of the dataset.
Question (8 - 9)
Statement
Let M, P, and C be a list of sequence numbers of students who have scored more than the
average marks in Mathematics, Physics and Chemistry respectively using the "Scores" dataset.
Answer question 8 and 9 after executing the following pseudocode.

1 seqDict = {}
2 foreach index in M{
3 seqDict[index] = 0
4 }
5
6 foreach index in P{
7 if(isKey(seqDict, index)){
8 seqDict[index] = seqDict[index] + 1
9 }
10 }
11
12 foreach index in C{
13 if(isKey(seqDict, index)){
14 seqDict[index] = seqDict[index] + 1
15 }
16 }

Explanation
Line 3: If a student scores more than average in Mathematics, the sequence number of the
student is being stored in dictionary and is being mapped to 0.

Line 7: The statement will only be True when the sequence number of the student is already a key
of seqDict.

Line 13: The statement will only be True when the sequence number of the student is already a
key of seqDict.

This means a student's sequence number will be stored as key in seqDict, if and only if the
sequence number is in M.

Therefore, if a student's sequence number is a key of seqDict, then the student must have scored
more than average in Mathematics. If it is mapped to 0, means the student has more than
average only in Mathematics, as there is a possibility of the value being updated in line 8 or line
14 based on the students scores more or less than average in other two subjects.

If the student scored more than average in Mathematics and Physics only, then the sequence
number will be mapped to 1. This means line 8 is executed but line 14 is not executed, which
means the student did not score more than average in Chemistry.

If the student scored more than average in Mathematics and Chemistry only, then the sequence
number will be mapped to 1. This means line 14 is executed but line 8 is not executed, which
means the student did not score more than average in Physics.

If the student scored more than average in all three subjects, then the sequence number will be
mapped to 2. This means line 8 and line 14 both are executed.
Question 8 [4 Marks]
Statement
If seqDict[n] == 0 is a True statement, then choose the correct option(s) regarding the student
with sequence number n. It is a Multiple Select Question (MSQ).

Options
(a)

The student has scored more than the average marks in any one of the three subjects.

(b)

The student has not scored more than the average marks in any subject.

(c)

The student might have scored more than the average marks either in Physics or in Chemistry

(d)

The student has scored more than the average marks in Mathematics only

Answer
(d)
Question 9 [3 Marks]
Statement
If seqDict[n] == 1 is a True statement, then choose the correct option(s) regarding the student
with sequence number n. It is a Multiple Select Question (MSQ).

Options
(a)

The student has scored more than the average marks in Physics and Chemistry but not in
Mathematics .

(b)

The student has scored more than the average marks in Mathematics and might have scored
more than the average marks in Physics but not in Chemistry.

(c)

The student has scored more than the average marks in Mathematics and might have scored
more than the average marks in Chemistry but not in Physics.

(d)

The student has scored more than average marks in any two of three subjects.

Answer
(b), (c)
Question 10 [4 Marks]
Statement
The following pseudocode is executed using the "Words" dataset. Let unique(L) returns the list of
unique elements of L. What will wCount represent at the end of the execution of the
pseudocode? Ignore the upper and lower case, and punctuation symbols while comparing with
other words.

1 wList = [], uniqueList = []


2 wCount = {}
3 while(Table 1 has more rows){
4 Read the first row X from Table 1
5 wList = wList ++ [X.Word]
6 if(X.Word ends with a full stop){
7 uniqueList = unique(wList)
8 foreach word in uniqueList{
9 if(isKey(wCount, word)){
10 wCount[word] = wCount[word] + 1
11 }
12 else{
13 wCount[word] = 1
14 }
15 }
16 wList = []
17 }
18 Move X to table 2
19 }

Options
(a)

Dictionary with words as keys mapped to the number of sentences in which the word is present.

(b)

Dictionary with words as keys mapped to the frequency count of the word in the dataset.

(c)

Dictionary with words as keys mapped to the maximum frequency of the word in a sentence.

(d)

Dictionary with words as keys mapped to the number of sentences in which the word is present
more than one time.
Answer
(a)

Solution
Line 5: wList stores the list of each word of dataset. But wList is being re-initialized to an empty list
in line 16. Line 16 is executed whenever full stop comes into the picture. Therefore, wList stores
the list of words of the current sentence before it gets re-initialized.

Line 7: uniqueList = unique(wList), uniqueList stores the list of unique(distinct) words of the
current sentence.

Line 8: The loop is running for every element of uniqueList, which means the iteration will happen
for every unique word of the current sentence.

Line 9 - Line 14: If the word is seen first time till the current sentence, it is being mapped to 1 in
wCount. If it has been seen before then it would already be the key of wCount, then the value of
word will be incremented.

It is clear that for every word only one time the condition in line 9 will be checked because of
uniqueList. So the word appears first time then it is not a key. Which also means the word was not
present in any sentence before the current sentence. If the word's value gets incremented, this
means the word was seen before. As the value is being incremented by 1, and a word can be seen
only one time in a sentence, then actually it is being mapped to the number of sentences in which
the word was present.
Week-8, Graded Solution
Week-8, Graded Solution
Question-1 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-2 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-3 [6 Marks]
Statement
Answer
Solution
Question-4 [5 Marks]
Statement
Options
(a)
(b)
(c)
(d)
(e)
(g)
Answer
Solution
Question-(5 to 7) [11 Marks]
Statement
Question-5 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-6 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-7 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-(8 to 9) [7 Marks]
Statement
Question-8 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-9 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-10 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution

Question-1 [3 Marks]
Statement
The following pseudocode is executed using the "Scores" table. What will the values of A and B
represent at the end of the execution?

1 D = {}
2 while(Table 1 has more rows){
3 Read the fist row X in Table 1
4 if(isKey(D, X.Town/City)){
5 if(D[X.Town/City] > X.Mathematics){
6 D[X.Town/City] = X.Mathematics
7 }
8 }
9 else{
10 D[X.Town/City] = X.Mathematics
11 }
12 Move X to Table 2
13 }
14
15 A = 0, B = 100
16 foreach Y in keys(D){
17 if(B == D[Y]){
18 A = A + 1
19 }
20 if(B > D[Y]){
21 A = 1
22 B = D[Y]
23 }
24 }

Options
(a)

A = Cities where students score the highest marks in Mathematics


B = The highest marks in Mathematics

(b)

A = Number of cities where students score the highest marks in Mathematics


B = The highest marks in Mathematics

(c)

A = Number of cities where students score the lowest marks in Mathematics


B = The lowest marks in Mathematics

(d)

A = Always more than one


B = The highest marks in Mathematics

Answer
(c)

Solution
D is initialized as an empty dictionary. The scores table is iterated using the iterator X. In each
iteration, the if-condition check whether the X.CityTown is a key in D. If the condition evaluates to
True, then another if-condition (nested inside) checks whether
the Mathematics marks of X less than D[X.CityTown]. If the condition evaluates to true, then value
D[X.CityTown] is replaced by X.Mathematics. More precisely, D[X.CityTown] is updated by a new
value if X.Mathematics is lesser than it. Then, D[X.CityTown] stores the lowest mathematics mark of
students from X.CityTown. There is no else-block for the nested (inner) if-block. Then we come out
of the outer if-block.

The else-part of the outer if-block is executed when X.CityTown is not a key of D. Here, we create a
key X.CityTown in D, and initialize the value for the key as X.Mathematics. At the end of the while-
block, D captures the following information: For each CityTown C, D[C] is the lowest Mathematics
marks of the students from the city C.

Variables A and B are initialized with the value zero. The keys of D are iterated using the iterator
Y. In each iteration, The first if-condition checks whether B and D[Y] are same. If the condition
evaluates to True, then the value of A is incremented by one. The second if-condition checks B >
D[Y]. If the condition evaluates to True, then A is set to one and B is set to D[Y]. Based on the
usage of variables, A is used as a counter variable and Bis used to store some value and it is
updated when there is a smaller value than B is assigned for a key in D. Therefore, whenever a
key Y is encountered with B > D[Y], B is updated to D[Y], and A is set to one. Whenever a key
encountered with B == D[Y], the value of A is incremented by one.

Thus, B captures the lowest value among the values in D, and A captures the number of
occurrence of the lowest value. Since D captures the lowest mathematics marks of each city, A
and B capture the following information:
A = Number of cities where students score the lowest marks in Mathematics
B = The lowest marks in Mathematics
Question-2 [4 Marks]
Statement
The following pseudocode is executed using the "Scores" dataset. What will the value of B
represent at the end of the execution?

1 D = {}, B = 0
2 while(Table 1 has more rows){
3 Read the first row X in Table 1
4 D = updateDictByField(D, X.Physics)
5 Move X to Table 2
6 }
7 B = findAKey(D)
8
9 Procedure updateDictByField(D, Value)
10 if(isKey(D, Value)){
11 D[Value] = D[Value] + 1
12 }
13 else{
14 D[Value] = 1
15 }
16 return(D)
17 End updateDictByField
18
19 Procedure findAKey(D)
20 Key = -1, Value = 0
21 foreach A in keys(D){
22 if(D[A] > Value){
23 Value = D[A]
24 Key = A
25 }
26 }
27 return(Key)
28 End findAKey

Options
(a)

Number of repeated marks in Physics

(b)

Minimum marks in Physics

(c)

Maximum marks in Physics


(d)

Most frequent marks in Physics

Answer
(d)

Solution
First we loot at the procedure updateDictByField. The parameters passed to the procedure are a
dictionary and a value. The if-condition checks whether the Value is a key of D. If the condition
evaluates to True, then the value of D[Value] is incremented by one. Otherwise, D[Value] is
initialized with value one. Overall, the procedure updates the dictionary D as follows: if Value is
not a key then create it as a key of D and initialize with a value one, otherwise increment the value
of D[Value] by one.

Now, we look at the procedure findAKey. Given a parameter D, the procedure computes the
following: Two variables Key and Value are initialized with values -1 and 0. The keys of D are
iterated using the iterator A. During the iteration, Key captures the key which holds the maximum
value assigned in D, and Value captures the maximum value. At the end of the procedure, Key is
returned.

In the main pseudocode, D is initialized as an empty dictionary. The scores table is iterated using
an iterator X. In each step of iteration, the procedure updateDictByField is called with the
parameters D and X.Physics. At the end of the iteration, the keys of D are the Physics marks
scored by the students, and the values are the number of times each marks are scored by the
students. The procedure findAKey is called with the parameter D. It returns the key which
assigned with a maximum value. Since the keys of D are the Physics marks, the returned value
from the procedure is the Physics marks which is scored by maximum number of people.
Therefore, B captures the following information: Most frequent marks in Physics.
Question-3 [6 Marks]
Statement
The following pseudocode is executed using the "Scores" dataset. What will be the value of B at
the end of the execution?

1 D = {"Mathematics": {}, "Physics": {}, "Chemistry": }}, B = 0


2 while(Table 1 has more rows){
3 Read the first row X in Table 1
4 D = updateDictByField(D, X, "Mathematics")
5 D = updateDictByField(D, X, "Physics")
6 D = updateDictByField(D, X, "Chemistry")
7 Move X to Table 2
8 }
9
10 while(Table 2 has more rows){
11 Read the first row X in Table 2
12 if(eligible(D, X) > 1){
13 B = B + 1
14 }
15 Move X to Table 1
16 }
17
18 Procedure updateDictByField(D, Y, Subject)
19 if(isKey(D[Subject], Y.CityTown)){
20 if(D[Subject][Y.CityTown] < Y.Subject){
21 D[Subject][Y.CityTown] = Y.Subject
22 }
23 }
24 else{
25 D[Subject][Y.CityTown] = Y.Subject
26 }
27 return(D)
28 End updateDictByField
29
30 Procedure eligible(D, X)
31 SubList = ["Mathematics", "Physics", "Chemistry"], C = 0
32 foreach Subject in SubList{
33 if(D[Subject][X.CityTown] == X.Subject){
34 C = C + 1
35 }
36 }
37 return(C)
38 End eligible

Answer
10
Solution
The procedure updateDictByField receives a dictionary D, a row Y and a subject Subject as
parameters. First, we check whether Y.CityTown is a key in D[Subject]. If it evaluates to True, then
we update the value of the key Y.CityTown as Y.Subject when existing value of the key is less than
Y.Subject. That is, D captures the maximum marks of a student in the subject Subject in each city.

The procedure eligible receives the dictionary D and a student row X as parameters. For each
subject, we check whether the student is city topper in the subject where the maximum marks of
the subject in the city is stored in the dictionary D. Therefore, C captures the number of subjects
in which X is a city topper in the subject.
Question-4 [5 Marks]
Statement
The following pseudocode is executed using the "Shopping Bills" dataset. At the end of the
execution, the variable D captures the following information: for each customer Z, D[Z] ["Shop"]
stores the shops visited by Z, and D[Z] ["Category"] stores the categories of the items purchased
by Z. But the pseudocode may have mistakes. Identify all such mistakes (if any). It is a Multiple
Select Question (MSQ).

1 D = {}
2 while(Pile 1 has more cards){
3 Read the top card X in Pile 1
4 D = updateDictionary(D, X)
5 Move X to Pile 2
6 }
7
8 Procedure updateDictionary(D, Y)
9 if(not isKey(D, Y.CustomerName)){
10 D[Y.CustomerName] = {"Shop": [], "Category": []}
11 }
12 D[Y.CustomerName]["Shop"][Y.ShopName] = True
13 foreach A in Y.ItemList{
14 D[Y.CustomerName]["Shop"][A.Category] = True
15 }
16 return(D)
17 End updateDictionary

Options
(a)

Error in Line 1

(b)

Error in Line 10

(c)

Error in Line 13

(d)

Error in Line 14

(e)

Error in Line 16
(g)

No error

Answer
(b), (d)

Solution
The objective of the pseudocode is to nd the following: for each customer Z, find the shops visited
by Z, and the item categories which are bought by C. In the pseudocode, D is used to store the
above information. For each customer Z, D[Z] is a dictionary with keys "Shop" and "Category".
D[Z] ["Shop"] stores the shops that are visited by Z and D[Z] ["Category"] stores the categories of
the items purchased by Z. So, D[Z] ["Shop"] is a dictionary that assigns True value for all shop
visited by Z. Similarly, D[Z] ["Category"] is also a dictionary.

The first step is to read the cards and generate the dictionary D. Line 1 - 6 perform the reading
and invoke the procedure updateDictionary. Clearly, the pseudocode has no error in this part.

Let us look at the procedure updateDictionary. Here we have to update the dictionary fields for
the key Y.CustomerName. The first step is to check whether Y.CustomerName is a key in D. If it is
not a key, then create X.CustomerName as a key. The value for the key is defined as follows:

D[Y.CustomerName] = {"Shop": { }, "Category": { } }

In Line 9, the keys are assigned to empty lists. This is a mistake in the pseudocode. Therefore,

Error in Line 9:

Note that the keys are assigned to empty dictionaries since we encounter the customer for the
first time. If the customer name is exists in the keys list, then we move to the next step. Next we
have to add the shop name to the dictionary. This is done in Line 11. Note that the shop name is
already exists in the dictionary, then it overwrite the true assignment. It will not harm the
objective in any aspect. Finally, we check the item categories. Iterate the item list of the bill using
the iterator A. Add the item category to the dictionary in the field "Category" as follows:

D[Y.CustomerName] ["Category"] [A.Category] = True

In Line 13, the item category is added to the key "Shop". Therefore,

Error in Line 13:

At the end of the procedure, the updated dictionary D is returned.


Question-(5 to 7) [11 Marks]
Statement
The following pseudocode is executed using the "station wise" cards of the "Train" dataset. At the
end of the execution, STN captures the following information: for a station X, and a day of a week
A, STN[X] [A] stores the number of trains running through X on the day A. [Note: Assume that for
each station, the train list is given in a single card.]

1 STN = {}
2 while(Pile 1 has more cards){
3 Read the top card X in Pile 1
4 STN[X.StationName] = getInfo(STN, X)
5 Move X to Pile 2
6 }
7
8 Procedure getInfo(STN, X)
9 *********************
10 * Fill the code *
11 *********************
12 return(D)
13 End getInfo

Question-5 [4 Marks]
Statement
Choose the correct code fragment to complete the pseudocode.

Options
(a)

1 D = {}
2 foreach A in X.TrainList{
3 foreach B in A.Days{
4 D[B] = 1
5 }
6 }

(b)

1 D = {"M": 0, "Tu": 0, "W": 0, "Th": 0, "F": 0, "Sa": 0, "Su": 0}


2 foreach A in X.TrainList{
3 foreach B in A.Days{
4 D[B] = 1
5 }
6 }
(c)

1 D = {}
2 foreach A in X.TrainList{
3 foreach B in A.Days{
4 D[B] = D[B] + 1
5 }
6 }

(d)

1 D = {"M": 0, "Tu": 0, "W": 0, "Th": 0, "F": 0, "Sa": 0, "Su": 0}


2 foreach A in X.TrainList{
3 foreach B in A.Days{
4 D[B] = D[B] + 1
5 }
6 }

Answer
(d)

Solution
The dictionary STN captures the following information. For each station X, and for each day of a
week A, STN[X] [A] is an integer that represents the number of trains are running through X on
the day A. First we have to understand the structure of D. First of all, D is a dictionary where
stations are the keys. For each station X, STN[X] is another dictionary where days of a week are
the keys.

In the pseudocode, the cards are iterated using the iterator X. In each step of the iteration,
STN[X.StationName] is obtained from the procedure getInfo.

Now we look at the procedure getInfo. As we know that STN[X.StationName] is a dictionary, the
procedure getInfo should return a dictionary. Since it returns D, D should be a dictionary which
can be initialized as an empty dictionary.

D={}

With this initialization of D, we need to create/initialize keys when they found for the first time. If
the key already exists, then we can update the keys. But, none of our answers are checking the
existence of any key in D. Therefore, D should be initialized with keys and initial values for the
keys.

We know that the keys of D are days of a week. Then, the keys of D is fixed and the values are
non-negative integers. Therefore, D can be initialized as follows:

D = {"M": 0, "Tu": 0, "W": 0, "Th": 0, "F": 0, "Sa": 0, "Su": 0}

We assign the values are zero since no train is encountered for any day so far. Train list of the
station is iterated using the iterator A.

foreach A in X.TrainList

In each step of iteration, the running days of A is iterated using B.


foreach B in A.Days

For each day B, we have to increment one for D[B].

D[B] = D[B] + 1
Question-6 [3 Marks]
Statement
The following pseudocode is executed using the "station wise" cards of the "Train" dataset.
Consider the dictionary STN computed in the previous question. Choose the correct statement(s)
from the options based on the pseudocode. It is a Multiple Select Question (MSQ).

1 Z = {}, D = {}
2 foreach A in keys(STN){
3 C = 0, Y = 0
4 D = STN[A]
5 foreach B in keys(D){
6 if(Y == D[B]){
7 C = C + 1
8 }
9 if(Y < D[B]){
10 C = 1
11 Y = D[B]
12 }
13 }
14 if(not isKey(Z, C)){
15 Z[C] = 0
16 }
17 Z[C] = Z[C] + 1
18 }

Options
(a)

Keys of the dictionary Z is integer

(b)

There can be a value C such that Z[C] is zero

(c)

All values of the dictionary elements are non-zero

(d)

The number of keys in Z is 8

Answer
(a), (c)
Solution
First, we understand the pseudocode. D is initialized as an empty dictionary. keys(STN) is iterated
using the iterator A. In each step of iteration, D stores STN[A]. We know that STN[A] is a
dictionary. In the subsequent foreach-block, we find the maximum value assigned to any key and
number of times the value appeared in D. These information are stored in Y and C, respectively.

Once we computed C, we check whether C is a key in Z. Since C is an integer and Z[C] is also
assigned to an integer, both keys and values of Z are integers. Therefore,

Keys of the dictionary Z is integer:

Observe that the initial value of each key is set to zero. But in the next line, the value is
incremented by one. That is, for each key C, Z[C] is non-zero. Therefore,

All values of the dictionary elements are non-zero

C stores the maximum occurrence of the max value in dictionary D. Since keys of D are days of a
week, the maximum possible value of C is seven.
Question-7 [4 Marks]
Statement
Consider the dictionary STN computed in the previous question. Choose the correct pseudocode
to compute the number of stations which have trains passing through all days of a week.

Options
(a)

1 Z = 0
2 foreach A in keys(STN){
3 foreach B in keys(STN[A]){
4 if(STN[A][B] < 1){
5 C = False
6 }
7 }
8 if(C){
9 Z = Z + 1
10 }
11 }

(b)

1 Z = 0
2 foreach A in keys(STN){
3 C = True
4 foreach B in keys(STN[A]){
5 if(STN[A][B] < 1){
6 C = False
7 }
8 }
9 if(C){
10 Z = Z + 1
11 }
12 }

(c)

1 Z = 0
2 foreach A in keys(STN){
3 C = True
4 foreach B in keys(STN[A]){
5 if(STN[A][B] < 1){
6 C = False
7 }
8 else{
9 C = True
10 }
11 }
12 if(C){
13 Z = Z + 1
14 }
15 }

(d)

1 Z = 0
2 foreach A in keys(STN){
3 C = False
4 foreach B in keys(STN[A]){
5 if(STN[A][B] < 1){
6 C = True
7 }
8 }
9 if(C){
10 Z = Z + 1
11 }
12 }

Answer
(b)

Solution
For a station A and a day B, STN[A] [B] denotes the number of trains passing through the station
A on the day B. We iterate the keys of STN using A, and keys of STN[A] is iterated using B. The
role of C is to capture that the station A is busy on all days. Then, we should initialize C to True.

C = True

If we nd a day in which no trains are passing through station A, then we have to set C to False.
That is,

if(STN[A] [B] < 1){


C = True
}

The variable Z should be incremented when C remains True at the end of the iteration over the
keys of STN[A].

if(C){
Z=Z+1
}
Question-(8 to 9) [7 Marks]
Statement
The following pseudocode is executed using the "Words" dataset.

1 D = {}
2 while(Table 1 has more rows){
3 Read the first row X in Table 1
4 D = updateDictionary(D, X)
5 Move X to Table 2
6 }
7
8 Procedure updateDictionary(D, Y)
9 i = 1
10 while (i <= Y.LetterCount){
11 B = ith letter in Y.Word
12 if(isKey(D, B)){
13 D[B] = D[B] + 1
14 }
15 else{
16 D[B] = 1
17 }
18 i = i + 1
19 }
20 return(D)
21 End updateDictionary

Question-8 [3 Marks]
Statement
What will D represent at the end of the execution?

Options
(a)

Frequency count of each alphabet in the table

(b)

Frequency count of each word in the table

(c)

Most frequent alphabet in the table

(d)

Frequency count of each alphabet in each part of speech


Answer
(a)

Solution
First we consider the procedure updateDictionary. It receives a dictionary D and a word Y as
parameters. Based on the usage of D, keys of D are letters and values are integers. We iterate the
letters in the word Y using B. In the if-condition, we check whether the letter B is a key in D. If it
evaluates to True, then we increment the value of D[B] by one. Otherwise, add B as a key to D and
initialize its value to one. Therefore, we add the number of occurrence of each letter of Y to D.

In the main pseudocode, D is initialized as an empty dictionary. For each word X in the table, D
and X are passed to the procedure updateDictionary. Thus, the number of occurrence of each
letter in X is updated to the dictionary D.
Question-9 [4 Marks]
Statement
Consider the dictionary D and the procedure updateDictionary() in the previous question. Let
POS be a list that contains all part of speeches. Assume that given a dictionary D, there exists a
procedure max such that max(D) returns a list of keys which are mapped to the maximum value.
Choose the correct statement(s) from the options based on the following pseudocode. It is a
Multiple Select Question (MSQ).

1 C = {"Overall": max(D)}
2 foreach A in POS{
3 Move all rows to Table 1
4 B = {}
5 while (Table 1 has more rows){
6 Read the first row X in Table 1
7 if(X.PartOfSpeech == A){
8 B = updateDictionary(B, X)
9 }
10 Move X to Table 2
11 }
12 C[A] = max(B)
13 }

Options
(a)

length(keys(C)) is same as the number of different part of speeches in the input dataset

(b)

C captures the list of most frequent alphabet occurred overall in the dataset as well as for each
part of speech

(c)

C captures the most frequent alphabet occurred overall in the dataset as well as for each part of
speech

(d)

length(keys(C)) is one more than the number of different part of speeches in the dataset

Answer
(b), (d)
Solution
The variable C is declared as a dictionary and initialized with a key "Overall" with value as max(D)
where max(D) is a list of keys which are assigned to the maximum value. Therefore, max(D) is a
list of letters with maximum number of occurrence. As it defined, POS is a list of part of speeches.
POS is iterated using A. In each iteration, all the rows of "Words" table are moved to Table 1. Rows
in the table 1 are iterated using X. For each row X with part of speech as A, the dictionary D load
the number of occurrence of the letters in the word. That is, at the end of each iteration, B stores
the frequency count of letter in the words whose part of speech is A. max(B) will be stored as
value for the key A in C. That is,

C captures the list of most frequent alphabet occurred overall in the data set as well as for each
part of speech.

At the end of the execution, C will have length(POS) + 1 keys. Therefore,

length(keys(C)) is one more than the number of different part of speeches in the table.
Question-10 [4 Marks]
Statement
The following pseudocode is executed using the "Shopping bills" dataset. What will the value of D
represent at the end of the execution?

1 D = {}
2 while(Pile 1 has more cards){
3 Read the top card X in Pile 1
4 D = updateDictionary(D, X)
5 Move X to Pile 2
6 }
7
8 Procedure updateDictionary(D, Y)
9 foreach A in Y.ItemList{
10 C = A.ItemName
11 if(isKey(D, C)){
12 if(isKey(D[C], Y.ShopName)){
13 if(D[C][Y.ShopName]["Price"] != A.Price){
14 D[C][Y.ShopName]["Flag"] = True
15 }
16 }
17 else{
18 D[C][Y.ShopName] = {"Price": A.Price, "Flag" : False}
19 }
20 }
21 else{
22 D[C] = {}
23 D[C][Y.ShopName] = {"Price": A.Price, "Flag" : False}
24 }
25 }
26 return (D)
27 End updateDictionary

Options
(a)

For an item C, and a shop S, D[C] [S] ["Flag"] is set to True if and only if the item is sold for a
constant price

(b)

For an item C, and a shop S, D[C] [S] ["Flag"] is set to True if and only if the item is billed in more
than one bill

(c)

For an item C, and a shop S, D[C] [S] ["Flag"] is set to True if and only if the item is sold for variable
price
(d)

For an item C, and a shop S, D[C] [S] ["Flag"] is set to True if and only if the item is billed exactly
one bill

Answer
(c)

Solution
D is initialized as an empty dictionary. For each card X in the dataset, D is updated by the
procedure updateDictionary.

The procedure updateDictionary takes a dictionary and a card as parameters. For each item C in
the item list of Y, the if-condition checks whether C is a key in D. If the condition evaluates to True,
then check whether X.ShopName is a key in D[C]. If the condition evaluates to true, then set the
value for the key "Flag" to true when the value of the key "Price" is not equal to A.Price. Therefore,
in a shop S, for an item C, if C is sold for different prices in the shop S, then D[C] [S] ["Flag"] is set
to True.

For an item C, and a shop S, D[C] [S] ["Flag"] is set to True if and only if the item is sold for variable
price.
Week-9, Graded Answered
Week-9, Graded Answered
Question-(1 to 2) [4 Marks]
Statement
Question-1 [2 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Question-2 [2 Marks]
Statement
Options
(a)
(b)
(c)
(d)
(e)
Question-3 [2 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Question-(4 to 11) [8 Marks]
Statement
Question-4 [1 Mark]
Statement
Question-5 [1 Mark]
Statement
Question-6 [1 Mark]
Statement
Question-7 [1 Mark]
Statement
Question-8 [1 Mark]
Statement
Question-9 [1 Mark]
Statement
Question-10 [1 Mark]
Statement
Question-11 [1 Mark]
Statement
Question-12 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
(e)
Question-13 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Question-14 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)

Question-(1 to 2) [4 Marks]
Statement
Consider a graph generated from the "Scores" table that is represented by a matrix B. Each node
in the graph corresponds to a student from the table. SeqNo is used to label the nodes in the
graph. Study the given pseudocode and answer the following questions.

1 A = {}
2 while(Table 1 has more rows){
3 Read the first row X in Table 1
4 A[X.SeqNo] = [X.CityTown, X.Gender]
5 Move X to Table 2
6 }
7 n = length(keys(A))
8 B = createMatrix(n, n)
9 foreach i in keys(A){
10 foreach j in keys(A){
11 if(i != j and isRelated(A[i], A[j])){
12 B[i][j] = 1
13 }
14 }
15 }
16
17 Procedure isRelated(x, y)
18 if(first(x) == first(y) and last(x) == last(y)){
19 return(True)
20 }
21 else{
22 return(False)
23 }
24 End isRelated

Question-1 [2 Marks]
Statement
There is an edge between students i and j, with i j, if and only if:

Options
(a)

they are from the same city/town

(b)

they have the same gender

(c)

they are from the same city/town and have the same gender

(d)

they are from the same city/town or have the same gender
Question-2 [2 Marks]
Statement
Which of the following statements are true about this graph? It is a Multiple Select Question
(MSQ).

Options
(a)

There are two cliques in this graph, one for each gender

(b)

In every clique, there is at least a pair of students having different genders

(c)

All students in a given clique have the same gender

(d)

All students in a given clique are from the same city/town

(e)

There are no cliques in this graph


Question-3 [2 Marks]
Statement
The following table contains information regarding books in a library. Each row in the table
corresponds to a book and is authored by exactly two authors, with equal contributions from
both. There is a pool of n authors, each author being assigned a unique index between 0 and
. There are M books in total.

S.No Author-1 Author-2

0 4 0

... ... ...

5 33

The table is represented by a dictionary named books, with the keys as serial numbers and values
as the corresponding list of authors. Assume that books has already been computed. For
example, we have:

books[0] = [4, 0]

A graph G is generated from this table. Each node corresponds to an author. There is an edge
between authors i and j if and only if they have collaborated on a book. Given a pair of authors (i,
j), with i j, what does the value colab[i] [j] represent at the end of execution of the following
pseudocode? Assume that the number of authors, n, is given to you.

1 colab = createMatrix(n, n)
2 foreach i in keys(books){
3 auth1 = first(books[i])
4 auth2 = last(books[i])
5 colab[auth1][auth2] = colab[auth1][auth2] + 1
6 colab[auth2][auth1] = colab[auth2][auth1] + 1
7 }

Options
(a)

It represents the number of books published by authors i or j

(b)

It represents the number of books in which authors i and j have collaborated

(c)

It represents the number of books published by author i + number of books published by author j
(d)

It represents the number of books published by author i in which he has not collaborated with
author j
Question-(4 to 11) [8 Marks]
Statement
Using the matrix colab computed from the previous problem, answer the following questions. For
each question, what do the variables aVar and bVar represent at the end of execution of the
pseudocode? Pick the correct option from the table given below.

Answer Option

Maximum number of collaborators among all authors 1

An author with the maximum number of publications 2

A pair of authors who have collaborated most often 3

An author who has the maximum number of collaborators 4

Maximum number of books published by any pair of authors 5

The list of authors who have just one collaborator 6

Number of authors who have exactly one collaborator 7

Maximum number of books published by any author 8

Question-4 [1 Mark]
Statement

1 aVar = 0
2 bVar = []
3 foreach r in rows(colab){
4 foreach c in columns(colab){
5 if (colab[r][c] > aVar){
6 aVar = colab[r][c]
7 bVar = [r, c]
8 }
9 }
10 }

What is the correct option for variable aVar?

Question-5 [1 Mark]
Statement
What is the correct option for variable bVar?
Question-6 [1 Mark]
Statement

1 aVar = 0
2 bVar = 0
3 foreach r in rows(colab){
4 count = 0
5 foreach c in columns(colab){
6 if (colab[r][c] > 0){
7 count = count + 1
8 }
9 }
10 if(count > aVar){
11 aVar = count
12 bVar = r
13 }
14 }

What is the correct option for variable aVar?

Question-7 [1 Mark]
Statement
What is the correct option for variable bVar?

Question-8 [1 Mark]
Statement

1 aVar = 0
2 bVar = 0
3 foreach r in rows(colab){
4 count = 0
5 foreach c in columns(colab){
6 count = count + colab[r][c]
7 }
8 if(count > aVar){
9 aVar = count
10 bVar = r
11 }
12 }

What is the correct option for variable aVar?

Question-9 [1 Mark]
Statement
What is the correct option for variable bVar?

Question-10 [1 Mark]
Statement

1 aVar = 0
2 bVar = []
3 foreach r in rows(colab){
4 count = 0
5 foreach c in columns(colab){
6 if (colab[r][c] > 0){
7 count = count + 1
8 }
9 }
10 if(count == 1){}
11 aVar = aVar + 1
12 bVar = bVar ++ [r]
13 }
14 }

What is the correct option for variable aVar?

Question-11 [1 Mark]
Statement
What is the correct option for variable bVar?

Question-12 [4 Marks]
Statement
Continuing with the previous question, authors is a list of authors. isClique is a procedure that
determines if every pair of authors in this list have collaborated at least once. It returns False if at
least one pair of authors haven't collaborated, and True if every pair of authors have collaborated
at least once. Select the correct code fragment to complete the pseudocode. It is a Multiple Select
Question (MSQ).
1 Procedure isClique(authors, colab)
2 foreach i in authors{
3 foreach j in authors{
4 *********************
5 * Fill the code *
6 *********************
7 }
8 }
9 return(True)
10 End isClique

Options
(a)

1 if(i != j and colab[i][j] > 0){


2 return(False)
3 }

(b)

1 if (i != j and colab[i][j] == 0){


2 return(False)
3 }

(c)

1 if(i != j){
2 if(colab[i][j] == 1){
3 return (False)
4 }
5 }

(d)

1 if(i != j){
2 if(colab[i][j] == 0){
3 return(False)
4 }
5 }

(e)

1 if(i != j){
2 if(colab[i][j] == 0){
3 return(True)
4 }
5 }
Question-13 [3 Marks]
Statement
A computer scientist is planning to conduct an event in the city. She has come up with a novel
scheme to invite people:

The host (computer scientist) can send out any number of invitations and does not accept any
invitation.

Each invitation is represented by a unique text message.


Each invitee can choose to either accept or reject the invitation.
If an invitee accepts the invitation, then he can invite exactly one other person by forwarding
the invitation that he received to this person, i.e., the invitee can forward the message he
received only once.
If an invitee doesn't accept the invitation, he cannot invite anyone.
If a person receives multiple invitations, he can accept at most one of them. All other
invitations must be rejected.

This situation is modeled as a graph. There is a node corresponding to every person who attends
the event. n people attend the event and the attendees are indexed from 0 to . Given a pair
of attendees (i, j), there is an edge from i to j if and only if the following conditions are satisfied:

j was invited by i
j accepted i's invitation

The graph is represented by a matrix A, such that A[i] [j] = 1 if and only if there is an edge from i
to j.

For the case of n = 5, which of the following is a possible representation of the graph?

Options
(a)

(b)
(c)

(d)
Question-14 [4 Marks]
Statement
Continuing with the previous question, for a pair of attendees (i, j) other than the host, we say
that i is the ancestor of j, if their messages are identical and i has accepted the invitation before j.
Note that each invitation sent out by the host is a unique text message. Assume that the matrix A
that represents the graph has already been computed.

isAncestor is a procedure that accepts the matrix A and two attendees i and j other than the host
as input, with i j, and returns True if i is the ancestor of j, and False otherwise. Select the
correct code fragment to complete the pseudocode.

1 Procedure isAncestor(A, i, j)
2 k = i
3 flag = True
4 while(flag){
5 flag = False
6 foreach c in columns(A){
7 *********************
8 * Fill the code *
9 *********************
10 }
11 }
12 return(False)
13 End isAncestor

Options

(a)

1 if(A[k][c] == 1){
2 if(c == j){
3 return(True)
4 }
5 k = c
6 exitloop
7 }

(b)

1 if(A[k][c] == 1){
2 if(c == j){
3 return (True)
4 }
5 flag = True
6 exitloop
7 }
(c)

1 if(A[k][c] == 1){
2 if(c == j){
3 flag = True
4 return(True)
5 }
6 k = c
7 exitloop
8 }

(d)

1 if(A[k][c] == 1){
2 if(c == j){
3 return(True)
4 }
5 k = c
6 flag = True
7 exitloop
8 }
Week-11, Graded Assignment Solution
Week-11, Graded Assignment Solution
Question-1 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
(e)
Answer
Solution:
Question 2 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-3 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
(e)
(f)
Answer
Solution
Question-4 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question 5 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question- (6 - 7)
Statement
Question-6 [4 Mark]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-7 [3 Mark]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question (8 - 11)
Statement
Question-8 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question- 9 [3 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution
Question-10 [3 Mark]
Statement
Options
(a)
(b)
(c)
(d)
(e)
(f)
Answer
Solution:
Question-11 [4 Marks]
Statement
Options
(a)
(b)
(c)
(d)
Answer
Solution

Question-1 [3 Marks]
Statement
reverse is a recursive procedure to reverse a list. Select the correct code fragment to complete the
pseudocode given below. It is a Multiple Select Question (MSQ).

1 Procedure reverse(L)
2 if(length(L) <= 1){
3 return(L)
4 }
5 *********************
6 * Fill the code *
7 *********************
8 End reverse

Options
(a)

return ([last(L)] ++ reverse(init(L)))

(b)

return ([first(L)] ++ reverse(rest(L)))

(c)

return ([last(L)] ++ reverse(init(rest(L))) ++ [first(L)])

(d)

return ([first(L)] ++ reverse(init(rest(L))) ++ [last(L)])

(e)

return ([last(L)] ++ reverse(rest(init(L))) ++ [first(L)])

Answer
(a), (c), (e)
Solution:
Consider the following list:
[1, 2, 3, 4, 5]
We can think about two ways of reversing it.
Method-1
Move the last element to the first position in the list.
[5, 1, 2, 3, 4]
The first place in the list is now fixed and should not be altered. We can consider the remaining
places. Repeat the same operation of moving the last element to the first place of this truncated
list:
[5, 4, 1, 2, 3]
The first two places are now fixed. Repeating this operation one more time gives:
[5, 4, 3, 1, 2]
And once more:
[5, 4, 3, 2, 1]
This leaves us with the last element. Since this is already in the correct place, we are going to
leave it as it is.
[5, 4, 3, 2, 1]
Finally, we have:
[5, 4, 3, 2, 1]

In pseudocode, the way to achieve this is:


[last(L)] ++ reverse(init(L))
However, this statement in isolation is meaningless. It only makes sense if we plug it in the
procedure.

1 Procedure reverse(L)
2 if(length(L) <= 1){
3 return (L)
4 }
5 return([last(L)] ++ reverse(init(L)))
6 End reverse

The base-case of the recursion is when the list has only one element. In that case, there is nothing
to reverse, so we return the list as it is.

Method-2
Consider the same list that we had earlier: [1, 2, 3, 4, 5]. Another way to reverse the list is to swap
the first and last element:
[5, 2, 3, 4, 1]
Now, the first and last elements are in their place and must be left alone. We can continue
working with the elements in between. Applying the same procedure again:
[5, 4, 3, 2, 1]
The middle element is all that remains and it is already in the right place.
[5, 4, 3, 2, 1]
In pseudocode, we have:
[last(L)] ++ reverse(rest(init(L))) ++ [first(L)]
As before, this statement in isolation doesn’t make sense. So, we insert it into the correct place in
the pseudocode:
1 Procedure reverse(L)
2 if (length(L) <= 1) {
3 return (L)
4 }
5 return ([last(L)] ++ reverse(rest(init(L))) ++ [first(L)])
6 End reverse

The base case of the recursion captures two different conditions:

1. If there are an even number of elements to begin with, then we will reach a stage when the
list passed to reverse becomes empty in one of the recursive calls. At this stage, we just
return the empty list. As an example:
rest(init([1, 2, 3, 4])) = [2, 3]
rest(init([2, 3])) = [ ]

When we call reverse([ ]), we need to return the list as it is, which is empty in this case. This
case is represented by

length(L) == 0.

2. If there are an odd number of elements to begin with, then we will reach a stage when the
list passed to reverse has only one element. At this stage, we just return the singleton list.
rest(init([1, 2, 3, 4, 5])) = [2, 3, 4]
rest(init([2, 3, 4])) = [3]
When we call reverse([3]) we would like to return [3] as it is. This case is represented by
length(L) == 1.
The base case captures both these scenarios.
This particular method has two correct answers: options (c) and (e). This because, the
following statements are equivalent:
rest(init(L))
init(rest(L))
Question (2 - 4)
An auto-grading system for an online course is designed in the following way:

A student’s submission is recorded as a dictionary with the following keys

The “roll” key maps to the student’s roll number.


The “time” key maps to the time of submission
The “score” key maps to the student’s score for that submission
Each student can make multiple submissions before the deadline.

Every time a student makes a submission, the dictionary corresponding to it is


appended to the end of a list called scores.

An example:

1 scores = [{“roll”: 12, “time”: 10:20, “score”: 80 },


2 {“roll”: 20, “time”: 11:23, “score”: 70 },
3 {“roll”: 12, “time”: 20:40, “score”: 90 },
4 {“roll”: 12, “time”: 23:50, “score”: 95 },
5 {“roll”: 20, “time”: 23:53, “score”: 65 }]

Study the following pseudocode:

1 Procedure isPresent(L, roll)


2 foreach D in L{
3 if(D[“roll”] == roll){
4 return(True)
5 }
6 }
7 return(False)
8 End isPresent

1 Procedure getSubs(L)
2 if (length(L) <= 1){
3 return(L)
4 }
5 firstSub = first(L)
6 restSub = rest(L)
7 if(isPresent(restSub, firstSub[“roll”])){
8 return(getSubs(restSub))
9 }
10 else {
11 return([firstSub] ++ getSubs(restSub))
12 }
13 End getSubs

Answer questions 2 to 4 after executing the pseudocode given below:


1 scores = [ {“roll”: 12, “time”: 10:20, “score”: 80 },
2 {“roll”: 20, “time”: 11:23, “score”: 70 },
3 {“roll”: 12, “time”: 20:40, “score”: 90 },
4 {“roll”: 12, “time”: 23:50, “score”: 95 },
5 {“roll”: 20, “time”: 23:53, “score”: 65 } ]
6
7 submisssions = getSubs(scores)

Question 2 [4 Marks]
Statement
What is the value of submissions?

Options
(a)

[ {“roll”: 12, “time”: 10:20, “score”: 80 },

{“roll”: 20, “time”: 11:23, “score”: 70 } ]

(b)

[ {“roll”: 20, “time”: 11:23, “score”: 70 },

{“roll”: 12, “time”: 10:20, “score”: 80 } ]

(c)

[ {“roll”: 12, “time”: 23:50, “score”: 95 },

{“roll”: 20, “time”: 23:53, “score”: 65 } ]

(d)

[ {“roll”: 20, “time”: 23:53, “score”: 65 },

{“roll”: 12, “time”: 23:50, “score”: 95 } ]

Answer
(c)

Solution
The procedure getSubs is very similar to the procedure uniq that we looked at in the practice
assignment. Let us go through the recursive procedure step by step.

We are given that L is a list of dictionaries, where each dictionary corresponds to a submission.
The base case of the recursion returns the list as it is in one of the two cases: if the list is empty
(OR) if the list has exactly one element.

The rest of the code is as follows. The variable firstSub is the first submission in the list L. The
variable restSub is a list of all submissions but for the first one. Note that firstSub is a dictionary
and restSub is a list of dictionaries.
The if-else block checks if the roll number of the student who has made the submission stored in
the variable firstSub has made any other submissions. Let us have a closer look at this condition:

isPresent(restSub, firstSub[“roll”])

Note that this procedure is structurally similar to the member procedure. In member we pass
two parameters, a list and an element. member checks if the element is present in the list. In the
procedure isPresent, we are doing something similar. The first parameter is a list of submissions;
the second parameter is a single submission (dictionary). The procedure checks if this student has
made any other submissions. If yes, then the procedure returns True.

There is one recursive call in the if-block and another recursive call in the else-block. If the student
who has made the submission firstSub has made another submission in restSub, then we are
going to ignore the current submission (firstSub). After ignoring this submission, we are going to
recursively call the procedure on restSub.

If the student who has made firstSub has not made any other submission in restSub, then we
include this student’s submission in the final list of submissions we return. To this submission, we
append the return value of the recursive call executed on restSub.

If we keep executing this, we will see that for each student who is present in the list submissions,
we will retain the last submission made by this student, ignoring all the other submissions.
Question-3 [4 Marks]
Statement
What does the variable submissions represent?

Options
(a)

The list of all the submissions made by the students sorted in the ascending order of time.

(b)

The list of all the submissions made by the students sorted in the descending order of time.

(c)

The list of the last submissions made by the students sorted in the ascending order of time.

(d)

The list of the last submissions made by the students sorted in the descending order of time.

(e)

The list of the first submissions made by the students sorted in the ascending order of time.

(f)

The list of the first submissions made by the students sorted in the descending order of time.

Answer
(c)

Solution
The previous solution has largely covered the answer to this question. But let us spend some time
on why the last submissions are returned. This has to do with the if-else block. Notice that if the
roll number corresponding to the first submission (firstSub) has made another submission, then
this roll number will appear in at least one of the dictionaries in (restSub). So, if the procedure
isPresent returns the value True, then the student has made multiple submissions. In such a case
we are ignoring the first submission (firstSub) and return only the recursive call executed on the
rest of the elements:

return (getSubs(restSub))

On the other hand, if this student has made only one submission, we are going to include that. So,
we have:

return ([firstSub] ++ getSubs(restSubs))


Question-4 [4 Marks]
Statement
Assume that reverse is a procedure that reverses a list. Which of the following statements returns
the list of the first submissions made by the students sorted in the ascending order of time?

Options
(a)

getSubs(scores)

(b)

reverse(getSubs(scores))

(c)

getSubs(reverse(scores)))

(d)

reverse(getSubs(reverse(scores)))

Answer
(d)

Solution
We notice that getSubs returns the last submissions of all students. So, one way to get the first
submissions is to reverse the list scores and call getSubs on it:

getSubs(reverse(scores))

But this will give the first submissions sorted in descending order. To get the list of first
submissions made by the students sorted in ascending order of time, we need to reverse the
above list once again:

reverse(getSubs(reverse(scores)))
Question 5 [4 Marks]
Statement
outcomes is a list of strings that contains the information about the outcome of cricket matches
played by India in a tournament. Assume that each element in the list is either “win” or “loss”. For
example, if five matches have been played, then outcomes could look like this:

[“won”, “lost”, “lost”, “won”, “won”]

We call a list of outcomes a blank slate if the number of wins is equal to the number of losses.
blankSlate is a procedure that accepts outcomes as input and returns True if it is a blank slate
and False otherwise. Select the correct code fragment to complete the following pseudocode. It is
a Multiple Select Question (MSQ).

1 Procedure blankSlate(outcomes)
2 if(numeric(outcomes) == 0){
3 return(True)
4 }
5 else{
6 return(False)
7 }
8 End blankSlate
9
10 *********************
11 * Fill the code *
12 *********************

Options
(a)

1 Procedure numeric(L)
2 if(length(L) == 0){
3 return(0)
4 }
5 if(last(L) == “won”){
6 return(numeric(init(L)) + 1)
7 }
8 else{
9 return(numeric(init(L)) − 1)
10 }
11 End numeric

(b)
1 Procedure numeric(L)
2 if(length(L) == 0){
3 return (0)
4 }
5 if(last(L) == “won”){
6 return(numeric(rest(L)) + 1)
7 }
8 else{
9 return(numeric(rest(L)) − 1)
10 }
11 End numeric

(c)

1 Procedure numeric(L)
2 if(length(L) == 0){
3 return(0)
4 }
5 if(first(L) == “won”){
6 return(numeric(rest(L)) + 1)
7 }
8 else{
9 return(numeric(rest(L)) − 1)
10 }
11 End numeric
12

(d)

1 Procedure numeric(L)
2 if(length(L) == 0){
3 return(0)
4 }
5 if(first(L) == “won”){
6 return(numeric(init(L)) + 1)
7 }
8 else{
9 return(numeric(init(L)) − 1)
10 }
11 End numeric

Answer
(a), (c)

Solution
The basic idea in this solution is to represent “won” and “lost” as “+1” and “-1” respectively.
Switching to this representation, if there are an equal number of wins and losses, then the the
sum of all the entries in this new representation will be equal to zero. So, blankSlate is
transferring the computation to another procedure called numeric which helps us with this new
representation. If numeric(outcomes) is zero, then blankSlate returns True, and False
otherwise. Out task is to now complete numeric.
Let us look at one of the correct options and examine the code:

1 Procedure numeric(L)
2 if(length(L) == 0){
3 return(0)
4 }
5 if(first(L) == “won”){
6 return(numeric(rest(L)) + 1)
7 }
8 else{
9 return(numeric(rest(L)) − 1)
10 }
11 End numeric

The basic idea behind the solution is as follows. We partition the list into two parts: the first
element and the rest of the elements. first(L) could be either “won” or “lost”. In either case, we
recursively compute the output of numeric(rest(L)).

If first(L) is “won”, then we add one to the return value of numeric(rest(L)). If first(L) is “lost”, then
we subtract one from the return value of numeric(rest(L)).

Now, what does numeric(rest(L)) compute? Let us take an example. Let:

L = [“won”, “lost”, “lost”, “won”]

We want to see what numeric(rest(L)) computes. In this particular example, this is


numeric([“lost”, “lost”, “won”]). If we approach this inductively, we would like this output to be: (-1)
+ (-1) + 1 = -1. If we follow the recursive computation step by step, this is what is being computed.
Each line below traces one step of the recursive computation. Once we go all the way down, the
return value will be propagated back to the first call.

numeric([“won”, “lost”, “lost”, “won”])

numeric([“lost”, “lost”, “won”]) + 1

numeric([“lost”, “won”]) - 1 + 1

numeric([“won”]) - 1 - 1 + 1

numeric([ ]) + 1 - 1 - 1 + 1

0+1-1-1+1

The other solution to this problem is as follows:


1 Procedure numeric(L)
2 if(length(L) == 0){
3 return(0)
4 }
5 if(last(L) == “won”){
6 return(numeric(init(L)) + 1)
7 }
8 else{
9 return(numeric(init(L)) − 1)
10 }
11 End numeric
12

Here, we partition the list into the first n − 1 elements and the last element. The sequence of
recursive calls will be as follows:

numeric([“won”, “lost”, “lost”, “won”])

numeric([“won”, “lost”, “lost”]) + 1

numeric([“won”, “lost”]) - 1 + 1

numeric([“won”]) - 1 - 1 + 1

numeric([ ]) + 1 - 1 - 1 + 1

0+1-1-1+1

In both the solutions, the base case of the recursion kicks in when the list is empty. In such a case,
length(L) is zero. In such a situation, we return 0.
Question- (6 - 7)
Statement
2n chess players are participating in a tournament. Each player is given a unique participant ID
that is represented as a string. The player IDs are stored in a non-empty list players in the
descending order of their rating, i.e., the first element is the list has the ID of the player with the
highest rating.

The matches are scheduled as follows: The match is between the player from the top and
the player from the bottom of the rating list. We wish to create a list called matches which
stores the sequences of matches, starting with the first match and ending with the last match.
Each match is represented as a list of two players, the first element of which is the ID of the player
with the higher rating, while the second element is the ID of the player with lower rating. Assume
that no two players have the same rating.

Answer questions 6 and 7 based on this information

Question-6 [4 Mark]
Statement
matchThem is a recursive procedure that accepts players as argument and returns matches.
Select the correct implementation of the procedure. It is a Multiple Select Question (MSQ).

Options
(a)

1 Procedure matchThem(players)
2 if(length(players) == 2){
3 return([players])
4 }
5 else{
6 firstLast = [first(players), last(players)]
7 middle = init(rest(players))
8 return([firstLast] ++ matchThem(middle))
9 }
10 End matchThem

(b)
1 Procedure matchThem(players)
2 if(length(players) == 2){
3 return(players)
4 }
5 else{
6 firstLast = [first(players), last(players)]
7 middle = init(rest(players))
8 return([firstLast] ++ matchThem(middle))
9 }
10 End matchThem
11

(c)

1 Procedure matchThem(players)
2 if(length(players) == 0){
3 return([ ])
4 }
5 else {
6 firstLast = [first(players), last(players)]
7 middle = init(rest(players))
8 return([firstLast] ++ matchThem(middle))
9 }
10 End matchThem
11

(d)

1 Procedure matchThem(players)
2 if(length(players) == 0){
3 return([players])
4 }
5 else{
6 firstLast = [first(players), last(players)]
7 middle = init(rest(players))
8 return([firstLast] ++ matchThem(middle))
9 }
10 End matchThem
11

Answer
(a), (c)

Solution
matchThem is structurally very similar to the procedure to find if a string is a palindrome (this is
something we saw in the practice assignment). Let us analyze the correct answer:
1 Procedure matchThem(players)
2 if(length(players) == 2){
3 return([players])
4 }
5 else{
6 firstLast = [first(players), last(players)]
7 middle = init(rest(players))
8 return([firstLast] ++ matchThem(middle))
9 }
10 End matchThem

The basic idea is to pair the first and the last element of the list and then truncate the list by
ignoring the first and the last element. So, if our list is:

[a1, a2, · · · , an−1, an]

Then, we pair [a1, an]. This will be a pair of players who play a match. Now, we truncate the list to
get:

[a2, · · · , an−1]

The match is between the first and the last player, which is represented by:

firstLast = [first(players), last(players)]

rest(init(players)) will return all the elements in the list but for the last and first one. This is
stored in middle.

middle = rest(init(players))

To get the rest of the matches, we make the recursive call:

return([firstLast] ++ matchThem(middle))

Finally, we come to the base case of the recursion. This can be done in two ways. Let us look at
what happens to the length of the list as we keep removing the first and last element from it. We
keep subtracting 2 from 2n, we see the following sequence:

2n

2n − 2

2n − 4

...

We could either stop when the list has exactly two players. In this case, the base case will look like
this:

1 if(length(players) == 2){
2 return([players])
3 }
Note that we are returning [players] and not players. This is because we want the return value of
the procedure matchThem to be a list of lists. So, we can’t just return players, we need to
return[players].

At this stage, the list players will correspond to the last match, which is between players (n, n + 1).
Alternatively, we could keep going for one more step until the list is empty and do the following:

1 if(length(players) == 0){
2 return([ ])
3 }

In this case, we just return the empty list. Note that, when we reach this stage players will itself
be an empty list. So, if we return [players], it is the same as returning [ [ ] ], which is the list
containing an empty list. This is not what we want as we will end up adding an empty list as
another match!
Question-7 [3 Mark]
Statement
matchThem is a non-recursive procedure that accepts players as argument and returns
matches. Select the correct implementation of the procedure.

Options
(a)

1 Procedure matchThem(players)
2 matches = [ ]
3 while(length(players) > 0){
4 matches = matches ++ [[last(players), first(players)]]
5 players = rest(init(players))
6 }
7 return(matches)
8 End matchThem
9

(b)

1 Procedure matchThem(players)
2 matches = [ ]
3 while(length(players) > 0){
4 matches = matches ++ [[first(players), last(players)]]
5 players = rest(init(players))
6 }
7 return(matches)
8 End matchThem

(c)

1 Procedure matchThem(players)
2 matches = [ ]
3 while(length(players) >= 0){
4 matches = matches ++ [[first(players), last(players)]]
5 players = rest(init(players))
6 }
7 return(matches)
8 End matchThem

(d)
1 Procedure matchThem(players)
2 matches = [ ]
3 while(length(players) > 0){
4 matches = matches ++ [[first(players), last(players)]]
5 players = rest(players)
6 }
7 return(matches)
8 End matchThem

Answer
(b)

Solution
Question (8 - 11)
Statement
Consider the following graph with six nodes. A is a 6 × 6 matrix corresponding to this graph.
Assume that it has already been computed:

In the following pseudocode:

graph is a matrix
parents is a dictionary
sequence is a list

1 Procedure DFS(graph, parents, sequence, i)


2 sequence = sequence ++ [i]
3 foreach j in columns(graph){
4 if(graph[i][j] == 1 and not(isKey(parents, j))){
5 parents[j] = i
6 parents, sequence = DFS(graph, parents, sequence, j)
7 }
8 }
9 return(parents, sequence)
10 End DFS

Answer questions 8 to 11 using the information given above. In all questions, S represents a list, P
represents a dictionary, while A and B represent matrices.

Question-8 [4 Marks]
Statement
What will be the value of S after executing the following pseudocode?

1 P = { }
2 S = [ ]
3 P[0] = -1
4 P, S = DFS(A, P, S, 0)
Options
(a)

[0, 1, 2, 5, 3, 4]

(b)

[0, 1, 4]

(c)

[0, 1, 2, 3, 5, 4]

(d)

[0, 3, 1, 4, 5]

Answer
(c)

Solution
We are starting the DFS from node 0. Node 0 has two neighbors: 1 and 3. Since columns(graph)
returns the list of nodes in ascending order, we will visit node 1 before node 3. Since node 1 is not
a key in parents, the if-condition in the pseudocode will evaluate to True. Now, we will set
parents[1] = 0. This dictionary encodes the fact that we come to node 1 from node 0. In such a
case, we call 0 the parent of 1. We now make a recursive call from node 1.

Node 1 has three neighbors: 0, 2 and 4. As node 0 has already been visited, we move to node 2.
The parents dictionary is again updated and there is a recursive DFS call from node 2.

Node 2 has three neighbors: 1, 3, 5. As 1 has already been visited, the call now transfers to node
3.

Node 3 has two neighbors: 0 and 2. 0 and 2 have already been visited. So we have exhausted all
the neighbors of 3. At node 3 we have no more recursive calls. So the flow now returns to node 2.

From node 2 we continue where we left. Node 5 is still unvisited. We go ahead and visit that node.
Since all neighbors of node 5 have been exhausted, the call transfers back to node 2.

From node 2, we get back to node 1. At node 1, we see that node 4 is still unvisited. So we go
ahead and visit that node. Now, the call returns to node 1 and finally to node 0 from where it all
started.

The required sequence of nodes is: [0, 1, 2, 3, 5, 4]


Question- 9 [3 Marks]
Statement
What will be the value of nodes after executing the following pseudocode?

1 P = { }
2 S = [ ]
3 P[5] = -1
4 P, S = DFS(A, P, S, 5)
5 nodes = keys(P)

Options
(a)

[5, 2, 1, 0, 3, 4]

(b)

[5, 2, 1, 4, 0, 3]

(c)

[5, 2, 3, 0, 1, 4]

(d)

Cannot be determined

Answer
(d)

Solution
DFS on node 5 will happen in the following sequence:

[5, 2, 1, 0, 3, 4]

But keys(P) need not necessarily be equal to the above list. All that we can say is that every
element in the above list will be present in keys(P) and vice versa. The exact order in which
keys(P) returns the list of keys cannot be determined.
Question-10 [3 Mark]
Statement
Assume that sort is a procedure that accepts a list of integers as input and returns a sorted list in
ascending order. If 0 ≤ start ≤ 5, which of the following statements are true at the end of
execution of the following pseudocode? It is a Multiple Select Question (MSQ).

1 P = { }
2 S = [ ]
3 P[start] = -1
4 P, S = DFS(A, P, S, start)
5 nodes = sort(keys(P))

Options
(a)

nodes is equal to [0, 1, 2, 3, 4, 5]

(b)

S is equal to [0, 1, 2, 3, 4, 5]

(c)

The value of nodes is independent of start

(d)

The value of S is independent of start

(e)

The graph is connected.

(f)

The graph is not connected.

Answer
(a), (c), (e)

Solution:
First, this graph is connected. That is, every node is reachable from every other node. So, if we do
a DFS starting from any node, then we will end up visiting every one of the nodes. Therefore,
sort(keys(P)) will be equal to [0, 1, 2, 3, 4, 5] irrespective of the node from which we execute DFS.
So, nodes is independent of start. However, the sequence in which we visit the nodes will be
dependent on the node from which we start DFS. So, the value of S is NOT independent of start.
Question-11 [4 Marks]
Statement
Execute the following pseudocode

1 P = { }
2 S = [ ]
3 P[3] = -1
4 P, S = DFS(A, P, S, 3)
5 B = createMatrix(6, 6)
6 foreach i in keys(P){
7 if(i != 3){
8 parent = P[i]
9 B[parent][i] = 1
10 }
11 }

B is the matrix representation of which of the following graphs?

Options
(a)

(b)
(c)
(d)

Answer
(b)

Solution
Let us first look at the sequence in which the nodes are visited when we execute DFS starting
from node 3:

[3, 0, 1, 2, 5, 4]

We will revisit the terminology of parent-child. We call node i a parent of node j if j is visited for
the first time by traversing the edge from i to j. For example, we visit 0 for the first time by moving
from 3 to 0. Therefore, 3 becomes the parent of 0. Likewise, 0 becomes the child of 3. This parent-
child relationship is captured by the dictionary parents. After executing the above pseudocode, P
will look as follows:

P = {3: -1, 0: 3, 1: 0, 2: 1, 5: 2, 4: 1}

We now construct the adjacency matrix, B, for some graph. We need to figure out what that graph
is from the matrix. To that end, let us first see how the matrix is constructed.

In the dictionary P, each key corresponds to a node, and the corresponding value is the parent of
this node. The value of node 3 in P is -1. So it has no parent. This is because, we start the DFS
exploration from that node; so we set P[3] = -1 for that reason.

In the foreach loop, we iterate through all the six nodes. The if-condition inside the foreach loop
checks if i 3. For every other node i, we see what the parent of i is and store the result in
parent. Respecting the parent-child relationship, we draw an edge from the parent to the child.
This is given by the line: B[parent][i] = 1
So, the result of this computation is a directed tree with every node other 3 having a parent. All
the edges in this graph will be from a parent to a child.

You might also like