CT Ga
CT Ga
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 6: If total bill amount < 500 and total bill amount >= 100 then increment B
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.
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 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)
(b)
(c)
(d)
Answer
(d)
Solution
Let us analyze the given procedure, in step 2 two variables A and count are initialized to 0.
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 3: If Pile 1 is empty then stop the iteration and start from step 8
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: ---------------------------------------------------------------------------------------
Options
(a)
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 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 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
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?
(b)
(c)
(d)
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 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)
(b)
(c)
(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 2 Name 1
Row 3 Gender M
Row 6 Physics 45
Row 7 Chemistry 91
Options
(a)
(b)
(c)
(d)
(e)
(f)
(h)
Answer
(a), (b), (d), (e) and (h)
Solution
Row 1 is incorrect because it should be a number.
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.
Options
(a)
1: iv, 2: iii, 3: i, 4: iv
(b)
1: i, 2: iii, 3: i, 4: iii
(c)
(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)
(b)
(c)
(d)
Answer
(c)
Solution
Three input variables A, B and C are given. Then the variable X is initialized to 0.
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.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]
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
}
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
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]
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]
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 }
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)
}
}
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 = 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
}
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 }
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).
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.
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).
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.
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
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
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
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
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
}
}
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.
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)
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:
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?
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 }
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.
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 }
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 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.
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:
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
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.
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)]
}
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).
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”.
(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:
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.
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]
}
}
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 findAKey(D) {
Key = -1, Value = 0
foreach A in keys(D) {
if (D[A] > Value) {
Value = D[A]
Key = A
}
}
return (Key)
End findAKey
3. The following pseudocode is executed using the “Scores” table. What will be the value of B at
the end of execution? [6 Marks]
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 ??
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 ??
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,
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 ??
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:
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
foreach B in A.Days
D[B] = D[B] + 1
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
}
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,
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
}
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
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 ??
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)
(c)
(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.
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)
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.
(b)
(c)
(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)
(b)
(c)
(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:
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.
Options
(a)
(b)
(c)
(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)
(b)
(c)
(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.
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)
(b)
(c)
(d)
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)
(b)
(c)
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?
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:
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:
In Line 13, the item category is added to the key "Shop". Therefore,
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 = {}
2 foreach A in X.TrainList{
3 foreach B in A.Days{
4 D[B] = D[B] + 1
5 }
6 }
(d)
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:
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
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)
(b)
(c)
(d)
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,
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,
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,
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)
(b)
(c)
(d)
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.
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)
(b)
(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)
(c)
(d)
(e)
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)
(b)
(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
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 }
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 }
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 }
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 }
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)
(b)
(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.
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)
(b)
(c)
(d)
(e)
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]
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
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:
An example:
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
Question 2 [4 Marks]
Statement
What is the value of submissions?
Options
(a)
(b)
(c)
(d)
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:
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:
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)).
numeric([“lost”, “won”]) - 1 + 1
numeric([“won”]) - 1 - 1 + 1
numeric([ ]) + 1 - 1 - 1 + 1
0+1-1-1+1
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”]) - 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.
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:
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:
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))
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:
graph is a matrix
parents is a dictionary
sequence is a list
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.
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)
(b)
S is equal to [0, 1, 2, 3, 4, 5]
(c)
(d)
(e)
(f)
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 }
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.