1. 程式人生 > >檢視是否為等差序列

檢視是否為等差序列

刷知乎的時候看到的題目,思路是評論區大佬給的

有點像排序裡的計數排序法

程式碼如下

def isArithmeticSequence(A):
    B = [0] * len(A)
    min_value = min(A)
    max_value = max(A)
    d = (max_value - min_value) // (len(A) - 1)
    for i in A:
        if (i - min_value) % d == 0:
            seq_num = (i - min_value) // d
            B[seq_num] 
= 1 if sum(B) == len(A): return True else: return False if __name__ == '__main__': A = input("A sequence of numbers:\n") A = [i for i in map(int, A.strip().split())] if isArithmeticSequence(A): print("Yes") else: print('No')