gpt4 book ai didi

python - 如何找到具有最少步数的元素

转载 作者:行者123 更新时间:2023-12-05 08:35:49 26 4
gpt4 key购买 nike

如何计算到达特定索引的最小步数向前和向后计数?

列表是:

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 两次!

关于python - 如何找到具有最少步数的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72265938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com