如何计算到达特定索引的最小步数向前和向后计数?
列表是:
content = [1, 2, 3, 4, 5]
如果我从索引 0
开始并想知道要向前迭代多少步才能到达数字 4
我将得到 3
,因为:
#0 #1 #2 #3
[1, 2, 3, 4, 5]
但我也想倒过来知道,比如:
#0 #2 #1
[1, 2, 3, 4, 5]
在上面的示例中,最小步数是 2
另一个例子
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...
在上面的例子中,最小步数是1
注意:目标元素是唯一的。
最佳答案
在我看来,这是一个模数问题:
content = ["A", "B", "C", "D", "E"]
start_index = 4 # "E"
to_find = "D"
length = len(content)
difference = content.index(to_find) - start_index
print(min(difference % length, -difference % length))
请注意,我们只搜索 content
一次,不像一些解决方案,包括当前接受的解决方案,它搜索 content
两次!
https://stackoverflow.com/questions/72265938/