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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started