2

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.

2
  • #1 Rewrite the code without a found variable. #2 Rewrite the code so the only if statement is inside the while loop (this must be done as a result of #1) ... are you allowed the use of functions? Commented Mar 28, 2012 at 11:05
  • 2
    Doesn't this question belong to codereview.stackexchange.com? Commented Mar 28, 2012 at 11:08

2 Answers 2

1
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') 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that's exactly what i was looking for the only thing is does break count as a else clause?
to incorporate the else clause of the while statement, change the last line of code as 'else: print(X,'not found')'
1

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

1 Comment

This is the way to do the job at hand, but this does not appear to be an answer to the question ("First, use an else while-loop clause,…")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.