How do I make my code return the index of the smallest number rather than just the smallest number? This is what I've written:
def index_smallest(first):
minimum = first[0]
for x in first:
if x < minimum:
minimum = x
return minimum
How do I make my code return the index of the smallest number rather than just the smallest number? This is what I've written:
def index_smallest(first):
minimum = first[0]
for x in first:
if x < minimum:
minimum = x
return minimum
Change return minimum
to return first.index(minimum)
.
Or use
def index_smallest(first):
return first.index(min(first))
Demo:
>>> first = [1, 0, -1, 3]
>>> first.index(min(first))
2
For this just iterate over the available indices rather than the items in the list. You can do this by making a range()
iterable object based on the length of the list. Then you change all occurrances of x to be first[x] instead or grab the item each time like so:
def index_smallest(first):
minimum = first[0]
min_index = 0
for i in range(len(first)):
x = first[i]
if x < minimum:
minimum = x
min_index = i
return min_index
There's a more efficient way to do this, but your way works well enough.
This method uses emuerate()
to provide the index of each item. It requires only one pass over the sequence. It returns the index of the first item with the minimum value, or None
if the sequence is empty.
from operator import itemgetter
def index_smallest(seq):
value = itemgetter(1)
try:
return min(enumerate(seq), key=value)[0]
except ValueError as exc:
return None
>>> index_smallest('') is None
True
>>> index_smallest([10, 20, 1, -10, 32])
3
>>> index_smallest((i for i in [10, 20, 1, -10, 32])) # generator expression
3
>>> index_smallest('qwerty')
2
>>> index_smallest(iter('qwerty'))
2
This will also work with sequences that do not support subscripting, e.g. generators. It's debatable whether the position of an item in a spent generator is of any use, but I suppose there might be some use case for a finite generator. This code will handle all iterables and it will not blow up if an empty sequence is passed to it.
what you could do first is take the list of numbers and find the largest member. Then after that you can use the .index() method to obtain the corresponding index. For example:
my_numbers = [1,2,3,4,5,6]
greatest_number = max(my_numbers)
greatest_number_index = my_numbers.index(greatest_number)
print(greatest_number_index, greatest_number)