【py.checkio】Evenly Spaced Trees

题目:Evenly Spaced Trees - python coding challenges - Py.CheckiO

代码:

from typing import List

def evenly_spaced_trees(trees: List[int]) -> int:

    # 返回列表数值差
    C = [trees[i]-trees[i-1] for i in range(1,len(trees))]
    CC = C.copy()

    def gcd(a, b):
        """求最大公约数函数"""
        if a < b:
            a, b = b, a
        while b != 0:
            temp = a % b
            a = b
            b = temp
        return a

    # 求N个数最大公约数
    while len(C) != 1:
        a1 = C.pop()
        b1 = C.pop()
        c = gcd(a1, b1)
        C.append(c)

    return sum([d/C[0]-1 for d in CC]) if len(set(CC)) != 1 else 0

if __name__ == '__main__':
    print("Example:")
    print(evenly_spaced_trees([0, 2, 6]))
    assert evenly_spaced_trees([0, 2, 6]) == 1, 'add 1'
    assert evenly_spaced_trees([1, 3, 6]) == 3, 'add 3'
    assert evenly_spaced_trees([0, 2, 4]) == 0, 'no add'
    print("Coding complete? Click 'Check' to earn cool rewards!")

 

Guess you like

Origin blog.csdn.net/m0_37586703/article/details/122268408