0
myList=[1,2,3,5]
def findMax(aList):
     biggest = aList[0]
     for value in aList: 
           if value > biggest:
               biggest = value
     return biggest

This code searches for the largest number in a list.

How would I change this into a while loop, rather than a for loop?

4
  • 1
    why do you want that? and y not use max([1,2,3,4,5])? Commented Mar 3, 2014 at 21:36
  • It's an assignment in class, to see if we can change from a for loop to while. And I know about the max function, but we can't use that he said. :) I can't figure it out though. Commented Mar 3, 2014 at 21:37
  • 1
    set a variable (i) to index through the array. the condition for the while loop is i less than the size of the list. Increment i within the loop. Commented Mar 3, 2014 at 21:39
  • Consider putting the details from your comment (it is a homework assignment and that you need to solve this problem without a for loop or the max function) so people can understand where you're coming from. Commented Mar 3, 2014 at 22:01

4 Answers 4

1
myList=[1,2,3,5]
def findMax(aList):
     biggest = aList.pop()
     while(len(aList) > 0):
         element = aList.pop()
         if (element > biggest):
             biggest = element
     return biggest
Sign up to request clarification or add additional context in comments.

2 Comments

So each time the while loop runs len shrinks, because of pop?
Yup. If you don't specify in (), it will remove the last. See docs
0

What you can do is declare a simple counter before you go into the loop and then after you check if the value is greater than biggest, you add one to the counter. Make sure to check if the counter is equal to the size of the array though, so you don't go out of bounds of it. If it is, you can break out of the while loop.

Comments

0

Try this:

myList=[1,2,3,5]

def findMax(aList):
     i = 0
     biggest = aList[0]
     while (i < len(myList)):
          if myList[i] > biggest:
               biggest = value
          i += 1;
     return biggest

1 Comment

At least he put some code. ;) If ther eis code, then he deserve some answer
0
myList=[1,2,3,5]
def findMax(aList):
     biggest = aList[0]
     ii = 1
     while ii < len(aList): 
           if aList[ii] > biggest:
               biggest = aList[ii]
           ii += 1
     return biggest

Comments

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.