Question: Assignment 2 Consider the following code, which uses a while loop and found flag to search a list of powers of 2 for the value

Assignment 2

Consider the following code, which uses a while loop and found flag to search a list of powers of 2 for the value of 2 raised to the fifth power (32). Its stored in a module file called power.py.

L = [1, 2, 4, 8, 16, 32, 64]

X = 5

found = False

i = 0

while not found and i < len(L):

if 2 ** X == L[i]:

found = True

else:

i = i+1

if found:

print('at index', i)

else:

print(X, 'not found')

C:\book\tests> python power.py

at index 5

As is, the example doesnt follow normal Python coding techniques. Follow the steps outlined here to improve it (for all the transformations, you may either type your code interactively or store it in a script file run from the system command lineusing a file makes this exercise much easier):

First, rewrite this code with a while loop else clause to eliminate the found flag and final if statement. (2 marks)

Next, rewrite the example to use a for loop with an else clause, to eliminate

the explicit list-indexing logic. (Hint: to get the index of an item, use the list

index methodL.index(X) returns the offset of the first X in list L.) (2 marks)

Remove the loop completely by rewriting the example with a simple in

operator membership expression. (2 marks)

Use a for loop and the list append method to generate the powers-of-2 list (L) instead of hardcoding a list literal. (2 marks)

Do you think it would improve performance to move the 2 ** X expression

outside the loops? How would you code that? (2 marks)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!