문제

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?

올바른 솔루션이 없습니다

다른 팁

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

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.

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
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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top