Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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).

image.png 

 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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Systems analysis and design

Authors: kenneth e. kendall, julie e. kendall

8th Edition

135094909, 013608916X, 9780135094907, 978-0136089162

More Books

Students also viewed these Programming questions

Question

What are the benefits of studying psychology? (p. 17)

Answered: 1 week ago

Question

What are the three sections useful for simplifying a display?

Answered: 1 week ago

Question

How many complete meals do you eat daily?

Answered: 1 week ago