thechrishaddad
thechrishaddad

Reputation: 6735

convert this while loop to a more efficient while loop

i am trying to work this out is the simplest way, i am a beginner, this is the question i have been asked and the code:

Program logic alternatives. 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) It's 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:
    ('at index', i)
else:
     print(X,'not found')

The question it asked me to do is a couple but the first one is confusing me,

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

Any help is appreciated please. Thanks.

Upvotes: 2

Views: 278

Answers (2)

codetantra
codetantra

Reputation: 258

L = [1, 2, 4, 8, 16, 32, 64] 
X = 5 
i = 0 
while i < len(L): 
    if 2 ** X == L[i]: 
        print('at index',i)
        break;
    i = i+1 
    if i==len(L): print(X,'not found') 

Upvotes: 1

brice
brice

Reputation: 25039

Python comes with batteries

Use the index method:

L = [...]
try:
    i = L.index(2**X)
    print("idex: %d"%i)
except ValueError as err:
    print("not found")

Upvotes: 1

Related Questions