我正在帮助我的朋友在python中进行逻辑算法,但我还没有找到最佳解决方案。
首先,我有一个数组列表:
x = array[0,1,2,3,4,3,2,3,-2,-4,-7,2,2]
并且他想对x进行分类,因此输出变为如下:
array([0,1,2,3,4]) # increasing value
array([4,3,2]) #decreasing value
array([2,3]) # increasing value
array([3,-2,-4,-7]) #decreasing value
array([-7,2]) # increasing value
array([2,2]) # remain_the_same_value
规则很简单:
- 如果值继续增加(如上例:0,1,2,3,4),则将它们放入一个数组
- 如果值继续下降(如上例:3,-2,-4,-7),则将它们放入一个数组中
- 但是,如果值模式突然发生变化,例如上面的例子:从增加值(0,1,2,3,4)突然下一个值正在减少。将生成新数组并将最后一个增加的值(即4)监视下一个值,无论它是否为递减值。如果是,它们将被放入一个阵列中。例如:array([4,3,2])
- 如果值保持不变(例如上面的例子,从2到2)。它们将放在一个阵列中。
醇>
这是我到目前为止所做的,但距离解决方案还很远
#categorize which types of input
if len(x) > 2 :
for i in range(len(x)) :
if (x[i+1]-x[i]) > 0 and i+i < len(x) : # for increasing x value
elif (x[i+1]-x[i]) < 0 and i+i < len(x) : # for decreasing x value
elif (x[i+1]-x[i]) == 0 and i+i < len(x) : # for foward direction of vehicle
else :
print 'ERROR : check the input coordinates once again!'
最好的问候,
格伦
答案 0 :(得分:5)
首先,我想说我不理解你问题的一部分,
array([3,-2]) #decreasing value
array([-2,-4,-7]) #decreasing value
为什么这些是分开的?
到目前为止,我将发布我的答案,除了该部分之外,它给出了正确的结果,因为我没有看到它背后的逻辑。此示例使用列表和元组来简化,但如果需要,可以将其更改为使用数组。
>>> from itertools import groupby
>>> data = [0,1,2,3,4,3,2,3,-2,-4,-7,2,2]
>>> def slope(a,b): #Returns 1 for inc, 0 for equal and -1 for dec
return (a > b) - (a < b)
>>> def groups(nums):
for k,v in groupby(zip(nums,nums[1:]), lambda (x,y): slope(x,y)):
yield next(v) + tuple(y for x,y in v) #Using itertools.chain this can be written as tuple(chain(next(v),(y for x,y in v)))
>>> list(groups(data))
[(0, 1, 2, 3, 4), (4, 3, 2), (2, 3), (3, -2, -4, -7), (-7, 2), (2, 2)]
答案 1 :(得分:2)
我找到了运行更改的所有位置,然后生成包含两个端点的运行。
def sgn(x):
return (x > 0) - (x < 0)
def categorize(xs):
endpoints = [0]
endpoints.extend(i for i, x in enumerate(xs[1:-1], 1)
if sgn(x - xs[i - 1]) != sgn(xs[i + 1] - x))
endpoints.append(len(xs) - 1)
for e0, e1 in zip(endpoints, endpoints[1:]):
yield xs[e0:e1 + 1]
print list(categorize([0,1,2,3,4,3,2,3,-2,-4,-7,2,2]))
print list(categorize([0, 1, 2, 3]))
print list(categorize([0]))
答案 2 :(得分:0)
这个使用numpy怎么样,它同时解决了你的第二个问题。
import numpy as np x=(0, 1, 2, 3, 4, 3, 2, 3, -2, -4, -7, 2, 2) y=range(13) #First order differential, find slopes dx = list((np.diff(x)>0)*1) #First order differental looses first value, but we always want to keep it #just decide if it's lower or higher than the 2nd value d0=((x[0]-x[1])>0)*1 #Add the first order differential to the 2nd order differential (peaks) ddx = [d0,]+list(np.abs(np.diff(dx))) p=0 rx=[] ry=[] for n,v in enumerate(ddx): if v==1: rx.append(tuple(x[p:n+1])) ry.append(tuple(y[p:n+1])) p=n print rx print ry