Question
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
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).
Question 1: Rewrite the code with a while loop and an else clause to eliminate the found flag and final if statement.
Question 2: 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 method -- L.index(X) returns the offset of the first X in list L.
Question 3: Remove the for loop completely by rewriting the example with a simple in operator membership expression.
Question 4: Use a for loop and the list append method to generate the powers-of-2 list (L) instead of hardcoding a list literal
Question 5: Use a list comprehension and comment whether using a list comprehension makes the code more efficient.
In [ ]: L = [1,2,4,8,32,64] X = 5 found = False i = 0 while not found and i
Step by Step Solution
3.56 Rating (146 Votes )
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