質問

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