Reputation: 11
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?
Upvotes: 0
Views: 1086
Reputation: 2834
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
Upvotes: 1
Reputation: 23624
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
Upvotes: 0
Reputation: 1907
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
Upvotes: 0
Reputation: 1469
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.
Upvotes: 0