想知道一群的資料,是否都往同一個方向移動,解法:
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("case 1:", is_same_direction(10,20,30,40)) print("case 2:", is_same_direction(10,20,40,30)) print("case 3:", is_same_direction(40,30,20,10)) # allow small mistake. print("case 4:", 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/