How can I count the minimum steps to get to a specific index counting forward and backward?
The list is:
content = [1, 2, 3, 4]
If I start from index 0
and want to know how many steps to get to the number 4
iterating forwards I'll get 3
, because:
#0 #1 #2 #3
[1, 2, 3, 4, 5]
But I also want to know it backward, like:
#0 #2 #1
[1, 2, 3, 4, 5]
In the example above the minimum amount of steps is 2
Another example
content = ["A", "B", "C", "D", "E"]
start_index = 4 # "E"
to_find = "D"
#1 #2 #3 #4 #0
["A", "B", "C", "D", "E"]
# Moving forward I'll start from "A" again until reache "D"
#1 #0
["A", "B", "C", "D", "E"] # Moving backwards...
In the example above the minimum amount of steps is 1
CodePudding user response:
You could do:
len(content) - content.index(4)
Because content.index(4)
finds the "forward" index, and then the "backward" index equals the number of elements from the element 4
to the end of the list, which is the same as all of them minus the first content.index(4)
.
As noted in the comments, this finds the index of the first occurrence in the list. In order to find that of the last (i.e. first from the end), you might do:
content[::-1].index(4) 1
Example:
>>> content = ['a', 'b', 'c', 'b']
>>> len(content) - content.index('b')
3
>>> content[::-1].index('b') 1
1
CodePudding user response:
Simply decrement your index instead of incrementing it. Python lists support negative indexing
content = [1, 2, 3, 4, 5]
end_element = 4
i = 0
count = 0
while content[i] != end_element:
i -= 1
count = 1
print(count) # 2
Of course, this leaves the possibility of an IndexError: list index out of range
when the end_element
is not in your list, but you can handle that error pretty easily.
CodePudding user response:
Maybe this?
def m(l: list, n: int):
return min(l.index(n), len(l) - l.index(n))
Can your array have duplicated item? if so what's the behavior you want. e.g. what's the expectation of [1,2,3,4,3]?
In your example, the index start from 0 from the left and 1 from the right, which is a little odd.