How would I locate the index of the largest value in an array that the user inputs? Here is what I have:
def main():
numbers = eval(input("Give me an array of numbers: "))
largest = numbers[0]
How would I locate the index of the largest value in an array that the user inputs? Here is what I have:
def main():
numbers = eval(input("Give me an array of numbers: "))
largest = numbers[0]
max_index, max_value = max(enumerate(numbers), key=lambda pair: pair[1])
This does:
def main():
numbers = eval(input("Give me an array of numbers: "))
indices = [i for i, x in enumerate(my_list) if x == max(numbers)]
return indices
Runs as:
>>> indices = main()
Give me an array of numbers: [1, 5, 9, 3, 2, 9]
>>> indices
[2, 5]
This code uses list comprehension to loop over the list and see where the maximum value(s) are using max(). This also accounts for the fact that there might be more than one of the maximum value, e.g. [1, 5, 9, 3, 2, 9], 9 appears twice.