Python 判斷一群的點,是否往同一個方向

想知道一群的資料,是否都往同一個方向移動,解法:


def average(lst): 
    return sum(lst) / len(lst) 

def is_same_direction_list(args,deviation=0):
    ret = True
    args_average=average(args)
    #print("args_average:", args_average)

    direction = -1
    if args[0] <= args_average:
        direction = 1
    
    idx=0
    args_count = len(args)
    for item in args:
        idx+=1
        if idx == args_count:
            break

        if direction==1:
            if (args[idx]+deviation)<item and (args[idx]-deviation)<item:
                ret = False
                break
        else:
            if (args[idx]+deviation)>item and (args[idx]-deviation)>item:
                ret = False
                break

    return ret

def is_same_direction(*args,deviation=0):
    return is_same_direction_list(args,deviation=deviation)


print(&quot;case 1:&quot;, is_same_direction(10,20,30,40))
print(&quot;case 2:&quot;, is_same_direction(10,20,40,30))
print(&quot;case 3:&quot;, is_same_direction(40,30,20,10))

# allow small mistake.
print(&quot;case 4:&quot;, is_same_direction(10,20,33,30,deviation=3))

執行結果:

 case 1: True
 case 2: False
 case 3: True
 case 4: True

成功讓 case 4 號變成 True, 允許小範圍的誤差.


技術原理:

Python不定長度參數args,*kwargs
https://stackoverflow.max-everyday.com/2020/03/python-function-args-kwargs/

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *