首页 > 解决方案 > 在Python中查找循环列表中点之间的前向距离

问题描述

我将使用的一个示例圆形列表是[0, 1, 2, 3, 4, 5, 6, 7],类似于棋盘游戏中的正方形,其中正方形 0 跟随正方形 7。我试图通过仅向前移动而不是最小距离来找到任意两点之间的距离. 例如,0 和 7 之间的距离为 7,但 7 和 0 之间的距离为 1。7 和 7 之间的距离为 0,依此类推。我曾尝试使用迭代器中的循环生成器,但无法提出解决方案,因为我不明白如何解决这个问题。我真的很感激任何帮助,非常感谢:)!

标签: pythonloopscombinations

解决方案


尝试这样的事情......

numbers = [0, 1, 2, 3, 4, 5, 6, 7]

def fxn(point_a, point_b):
    count = 0
    position = numbers.index(point_a)
    while numbers[position] != point_b:
        if position + 1 == len(numbers):
            position = 0
            count += 1
        else:
            position += 1
            count += 1
    return count

推荐阅读