0% found this document useful (0 votes)
873 views18 pages

Rewrite The Following Code Fragment That Saves On The Number of Comparisons

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
873 views18 pages

Rewrite The Following Code Fragment That Saves On The Number of Comparisons

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Rewrite the following code fragment that saves on the number of comparisons:

if (a == 0) :
print ("Zero")
if (a == 1) :
print ("One")
if (a == 2) :
print ("Two")
if (a == 3) :
print ("Three")

Answer

if (a == 0) :
print ("Zero")
elif (a == 1) :
print ("One")
elif (a == 2) :
print ("Two")
elif (a == 3) :
print ("Three")

Question 2

Under what conditions will this code fragment print "water"?

if temp < 32 :
print ("ice")
elif temp < 212:
print ("water")
else :
print ("steam")

Answer

When value of temp is greater than or equal to 32 and less than 212 then this code
fragment will print "water".

Question 3

What is the output produced by the following code?

x=1
if x > 3 :
if x > 4 :
print ("A", end = ' ')
else :
print ("B", end = ' ')
elif x < 2:
if (x != 0):
print ("C", end = ' ')
print ("D")

Answer

Output

CD

Explanation

As value of x is 1 so statements in the else part of outer if i.e. elif x < 2: will get
executed. The condition if (x != 0) is true so C is printed. After that the
statement print ("D") prints D.

Question 4

What is the error in following code? Correct the code:

weather = 'raining'
if weather = 'sunny' :
print ("wear sunblock")
elif weather = "snow":
print ("going skiing")
else :
print (weather)

Answer

In this code, assignment operator (=) is used in place of equality operator (==) for
comparison. The corrected code is below:

weather = 'raining'
if weather == 'sunny' :
print ("wear sunblock")
elif weather == "snow":
print ("going skiing")
else :
print (weather)

Question 5

What is the output of the following lines of code?

if int('zero') == 0 :
print ("zero")
elif str(0) == 'zero' :
print (0)
elif str(0) == '0' :
print (str(0))
else:
print ("none of the above")

Answer

The above lines of code will cause an error as in the line if int('zero') == 0 :, 'zero' is
given to int() function but string 'zero' doesn't have a valid numeric representation.

Question 6

Find the errors in the code given below and correct the code:

if n == 0
print ("zero")
elif : n == 1
print ("one")
elif
n == 2:
print ("two")
else n == 3:
print ("three")

Answer

The corrected code is below:

if n == 0 : #1st Error
print ("zero")
elif n == 1 : #2nd Error
print ("one")
elif n == 2: #3rd Error
print ("two")
elif n == 3: #4th Error
print ("three")

Question 7

What is following code doing? What would it print for input as 3?

n = int(input( "Enter an integer:" ))


if n < 1 :
print ("invalid value")
else :
for i in range(1, n + 1):
print (i * i)

Answer

The code will print the square of each number from 1 till the number given as input
by the user if the input value is greater than 0. Output of the code for input as 3 is
shown below:
Enter an integer:3
1
4
9

Question 8

How are following two code fragments different from one another? Also, predict the
output of the following code fragments :

(a)

n = int(input( "Enter an integer:" ))


if n > 0 :
for a in range(1, n + n ) :
print (a / (n/2))
else :
print ("Now quiting")

(b)

n = int(input("Enter an integer:"))
if n > 0 :
for a in range(1, n + n) :
print (a / (n/2))
else :
print ("Now quiting")

Answer

In part (a) code, the else clause is part of the loop i.e. it is a loop else clause that
will be executed when the loop terminates normally. In part (b) code, the else clause
is part of the if statement i.e. it is an if-else clause. It won't be executed if the user
gives a greater than 0 input for n.

Output of part a:

Enter an integer:3
0.6666666666666666
1.3333333333333333
2.0
2.6666666666666665
3.3333333333333335
Now quiting
Output of part b:

Enter an integer:3
0.6666666666666666
1.3333333333333333
2.0
2.6666666666666665
3.3333333333333335

Question 9a

Rewrite the following code fragment using for loop:

i = 100
while (i > 0) :
print (i)
i -= 3

Answer

for i in range(100, 0, -3) :


print (i)

Question 9b

Rewrite the following code fragment using for loop:

while num > 0 :


print (num % 10)
num = num/10

Answer

l = [1]
for x in l:
l.append(x + 1)
if num <= 0:
break
print (num % 10)
num = num/10

Question 9c

Rewrite the following code fragment using for loop:

while num > 0 :


count += 1
sum += num
num –= 2
if count == 10 :
print (sum/float(count))
break

Answer

for i in range(num, 0, -2):


count += 1
sum += i
if count == 10 :
print (sum/float(count))
break

Question 10a

Rewrite following code fragment using while loops :

min = 0
max = num
if num < 0 :
min = num
max = 0 # compute sum of integers
# from min to max

for i in range(min, max + 1):


sum += i

Answer

min = 0
max = num
if num < 0 :
min = num
max = 0 # compute sum of integers
# from min to max
i = min
while i <= max:
sum += i
i += 1

Question 10b

Rewrite following code fragment using while loops :

for i in range(1, 16) :


if i % 3 == 0 :
print (i)

Answer

i=1
while i < 16:
if i % 3 == 0 :
print (i)
i += 1

Question 10c
Rewrite following code fragment using while loops :

for i in range(4) :
for j in range(5):
if i + 1 == j or j + 1 == 4 :
print ("+", end = ' ')
else :
print ("o", end = ' ')
print()

Answer

i=0
while i < 4:
j=0
while j < 5:
if i + 1 == j or j + 1 == 4 :
print ("+", end = ' ')
j += 1
else :
print ("o", end = ' ')
i += 1
print()

Question 11a

Predict the output of the following code fragments:

count = 0
while count < 10:
print ("Hello")
count += 1

Answer

Output

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello

Explanation
The while loop executes 10 times so "Hello" is printed 10 times

Question 11b

Predict the output of the following code fragments:

x = 10
y=0
while x > y:
print (x, y)
x=x-1
y=y+1

Answer

Output

10 0
91
82
73
64

Explanation

x y Output Remarks

10 0 10 0 1st Iteration

10 0
9 1 2nd Iteration
91

10 0
8 2 91 3rd Iteration
82

10 0
91
7 3 4th Iteration
82
73

10 0
91
6 4 82 5th Iteration
73
64
Question 11c

Predict the output of the following code fragments:

keepgoing = True
x=100
while keepgoing :
print (x)
x = x - 10
if x < 50 :
keepgoing = False

Answer

Output

100
90
80
70
60
50

Explanation

Inside while loop, the line x = x - 10 is decreasing x by 10 so after 5 iterations of


while loop x will become 40. When x becomes 40, the condition if x < 50 becomes
true so keepgoing is set to False due to which the while loop stops iterating.

Question 11d

Predict the output of the following code fragments:

x = 45
while x < 50 :
print (x)

Answer

This is an endless (infinite) loop that will keep printing 45 continuously.

As the loop control variable x is not updated inside the loop neither there is any
break statement inside the loop so it becomes an infinite loop.

Question 11e

Predict the output of the following code fragments:

for x in [1,2,3,4,5]:
print (x)

Answer
Output

1
2
3
4
5

Explanation

x will be assigned each of the values from the list one by one and that will get
printed.

Question 11f

Predict the output of the following code fragments:

for x in range(5):
print (x)

Answer

Output

0
1
2
3
4

Explanation

range(5) will generate a sequence like this [0, 1, 2, 3, 4]. x will be assigned each of
the values from this sequence one by one and that will get printed.

Question 11g

Predict the output of the following code fragments:

for p in range(1,10):
print (p)

Answer

Output

1
2
3
4
5
6
7
8
9

Explanation

range(1,10) will generate a sequence like this [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]. p will be


assigned each of the values from this sequence one by one and that will get printed.

Question 11h

Predict the output of the following code fragments:

for q in range(100, 50, -10):


print (q)

Answer

Output

100
90
80
70
60

Explanation

range(100, 50, -10) will generate a sequence like this [100, 90, 80, 70, 60]. q will be
assigned each of the values from this sequence one by one and that will get printed.

Question 11i

Predict the output of the following code fragments:

for z in range(-500, 500, 100):


print (z)

Answer

Output

-500
-400
-300
-200
-100
0
100
200
300
400

Explanation

range(-500, 500, 100) generates a sequence of numbers from -500 to 400 with each
subsequent number incrementing by 100. Each number of this sequence is assigned
to z one by one and then z gets printed inside the for loop.

Question 11j

Predict the output of the following code fragments:

for y in range(500, 100, 100):


print (" * ", y)

Answer

This code generates No Output.

The for loop doesn't execute as range(500, 100, 100) returns an empty sequence —
[ ].

Question 11k

Predict the output of the following code fragments:

x = 10
y=5
for i in range(x-y * 2):
print (" % ", i)

Answer

This code generates No Output.

Explanation

The x-y * 2 in range(x-y * 2) is evaluated as below:


x-y*2
⇒ 10 - 5 * 2
⇒ 10 - 10 [∵ * has higher precedence than -]
⇒0

Thus range(x-y * 2) is equivalent to range(0) which returns an empty sequence — [ ].

Question 11l

Predict the output of the following code fragments:

for x in [1,2,3]:
for y in [4, 5, 6]:
print (x, y)

Answer

Output

1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6

Explanation

For each iteration of outer loop, the inner loop will execute three times generating
this output.

Question 11m

Predict the output of the following code fragments:

for x in range(3):
for y in range(4):
print (x, y, x + y)

Answer

Output

0 0 0
0 1 1
0 2 2
0 3 3
1 0 1
1 1 2
1 2 3
1 3 4
2 0 2
2 1 3
2 2 4
2 3 5

Explanation

For each iteration of outer loop, the inner loop executes four times (with value of y
ranging from 0 to 3) generating this output.
Question 11n

Predict the output of the following code fragments:

c=0
for x in range(10):
for y in range(5):
c += 1
print (c)

Answer

Output

50

Explanation

Outer loop executes 10 times. For each iteration of outer loop, inner loop executes 5
times. Thus, the statement c += 1 is executed 10 * 5 = 50 times. c is incremented by
1 in each execution so final value of c becomes 50.

Question 12

What is the output of the following code?

for i in range(4):
for j in range(5):
if i + 1 == j or j + i == 4:
print ("+", end = ' ')
else:
print ("o", end = ' ')
print()

Answer

Output

o+oo+oo++ooo++oo+oo+

Explanation

Outer loop executes 4 times. For each iteration of outer loop, inner loop executes 5
times. Therefore, the total number of times body of inner loop gets executed is 4 * 5
= 20. Thats why there are 20 characters in the output (leaving spaces). When the
condition is true then + is printed else o is printed.

Question 13

In the nested for loop code below, how many times is the condition of the if clause
evaluated?
for i in range(4):
for j in range(5):
if i + 1 == j or j + i == 4:
print ("+", end = ")
else:
print ("o", end = ")
print()

Answer

Outer loop executes 4 times. For each iteration of outer loop, inner loop executes 5
times. Therefore, the total number of times the condition of the if clause gets
evaluated is 4 * 5 = 20.

Question 14

Which of the following Python programs implement the control flow graph shown?
(a)

while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
else :
print ("what")
else:
print ("ever")

(b)
while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
else :
print ("what")
print ("ever")

(c)

while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
print ("what")
print ("ever")

Answer

Python program given in Option (b) implements this flowchart:

while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
else :
print ("what")
print ("ever")

Question 15

Find the error. Consider the following program :

a = int(input("Enter a value: "))


while a != 0:
count = count + 1
a = int(input("Enter a value: "))
print("You entered", count, "values.")

It is supposed to count the number of values entered by the user until the user
enters 0 and then display the count (not including the 0). However, when the
program is run, it crashes with the following error message after the first input value
is read :
Enter a value: 14
Traceback (most recent call last):
File "count.py", line 4, in <module>
count = count + 1
NameError: name 'count' is not defined
What change should be made to this program so that it will run correctly ? Write the
modification that is needed into the program above, crossing out any code that
should be removed and clearly indicating where any new code should be inserted.

Answer

The line count = count + 1 is incrementing the value of variable count by 1 but the
variable count has not been initialized before this statement. This causes an error
when trying to execute the program. The corrected program is below:
count = 0 #count should be initialized before incrementing
a = int(input("Enter a value: "))
while a != 0:
count = count + 1
a = int(input("Enter a value: "))
print("You entered", count, "values.")

You might also like