Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding turning points of an Array in python

If I for example have an array:

A = (0,2,3,4,5,2,1,2,3,4,5,6,7,8,7,6,5,4,5,6)

It can be seen that there are 4 turning points. (at A[4],A[6], A[13], A[17])

How can I use python to return the number of turning points?

import numpy as np
import scipy.integrate as SP
import math

def turningpoints(A):
    print A
    N = 0
    delta = 0
    delta_prev = 0
    for i in range(1,19):
        delta = A[i-1]-A[i]       #Change between elements
        if delta < delta_prev:    #if change has gotten smaller
            N = N+1               #number of turning points increases
        delta_prev = delta        #set the change as the previous change
    return N

if __name__ == "__main__":
    A  = np.array([0,2,3,4,5,2,1,2,3,4,5,6,7,8,7,6,5,4,5,6])
    print turningpoints(A)

Currently, this system is flawed and certainly not very elegant. Any ideas?

like image 771
user2984189 Avatar asked Dec 02 '22 17:12

user2984189


1 Answers

If you have numpy:

def turningpoints(lst):
    dx = np.diff(lst)
    return np.sum(dx[1:] * dx[:-1] < 0)

Or the non-numpy equivalent version:

def turningpoints(lst):
    dx = [x - y for x, y in zip(lst[1:], lst[:-1])]
    return sum(dx1 * dx2 < 0 for dx1, dx2 in zip(dx[1:], dx[:-1]))

And just for the love of one-liners:

def turningpoints(lst):
    return sum(x0*x1 + x1*x2 < x1*x1 + x0*x2 for x0, x1, x2 in zip(lst[2:], lst[1:-1], lst[:-2]))

But the readability is arguably decreased on this one :)

like image 186
val Avatar answered Dec 16 '22 11:12

val