Answer the question
In order to leave comments, you need to log in
How should this algorithm work?
I was reading Bkhargava "Groaking Algorithms" and came across this miracle
. How do you think the if block should be executed if smallest = 0? Naturally, I went to check and it just worked for me return
def smallest(arr):
smallest = arr[0]
smallest_index = 1 # Я специально поставил один чтобы увидеть что в конце оно выкинет один
for i in range(1,len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
d = [2,4,15,6,7,9,9]
print(smallest(d)) # 1
Answer the question
In order to leave comments, you need to log in
The algorithm is fully operational. Look at this example:
def smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1,len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
d = [4,15,6,2,7,9,9]
print(smallest(d)) # 3
print(d[smallest(d)]) # 2
smallest = arr[0]
smallest_index = 1 # I set one on purpose to see that it will throw one at the end
But you don’t need to set 1 on purpose when you need to set 0.
The meaning of the above algorithm is that we accept that the zero element of the array is the smallest. Accordingly, we remember that this minimum value is at index 0.
Then, starting from the first element, we look through the entire array and, if some element is less than the minimum, then 1) write down a new minimum and 2) remember its position.
And you take zero as the minimum element, but remember that it is in the second cell of the array (for some reason). And then you wonder why it doesn't work...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question