Write a function, max index, that takes a list as a parameter and returns the index of the largest number in the list. When writing the function, you are given the following rules:
- You are not allowed to use the max function
- You are not allowed to use any list methods
- You must use a Pythonic FOR loop. This means you CANNOT use the range function or enumerate function in your loop
- If the largest number appears more than once, you should return the smallest index
This is so wrong because it fails to loop through the list and I also don't know how to compare the two indexes in case the largest value appears more than once in the list.
def max_index(lon):
"""
input is a list of numbers.
returns the index of the largest number in the list
"""
max = lon[0]
index = 0
for n in lon:
if n>max:
max = n
index =1
return index
CodePudding user response:
This might not be the most effecient approach, but I'm pretty sure this would work:
def max_index(lon):
current_index = 0
largest_index = 0
max = 0
for item in lon:
if item > max:
max = item
largest_index = current_index
current_index = 1
return largest_index
CodePudding user response:
Here is one solution. If this is a homework question, you wont learn without trying, so try out different solutions starting with the for loop. Good luck!
def max_index(lon):
max_val=0
counter=0
max_index=0
for num in lon:
if num > max_val:
max_val = num
max_index = counter
counter = counter 1
return max_index