2013-10-31 82 views
0
class InterpolatedArray(object): 

    """An array-like object that provides 
    interpolated values between set points.""" 

    def __init__(self, points): 
    self.points = sorted(points) 

    def __getitem__(self, x): 
    if x > self.points[-1][0]: 
     return self.points[-1][1] + (x - self.points[-1][0]) * float((self.points[-1][1] - self.points[-2][1])/(self.points[-1][0] - self.points[-2][0])) 
    elif x < self.points[0][0]: 
     return self.points[0][1] + (x - self.points[0][0]) * float(self.points[1][1] - self.points[0][1]/(self.points[1][0] - self.points[0][0]) 
    else: 
     lower_point, upper_point = self._GetBoundingPoints(x) 
     return self._Interpolate(x, lower_point, upper_point) 

    def _GetBoundingPoints(self, x): 
    """Get the lower/upper points that bound x.""" 
    lower_point = None 
    upper_point = self.points[0] 
    for point in self.points[1:]: 
     lower_point = upper_point 
     upper_point = point 
     if x <= upper_point[0]: 
     break 
    return lower_point, upper_point 

    def _Interpolate(self, x, lower_point, upper_point): 
    """Interpolate a Y value for x given lower & upper 
    bounding points.""" 
    slope = (float(upper_point[1] - lower_point[1])/
      (upper_point[0] - lower_point[0])) 
    return lower_point[1] + (slope * (x - lower_point[0])) 

它只是抱怨「無效語法」中的行: 其他:簡單的Python語法錯誤

+3

你缺少前行上一個右括號。 – chepner

回答

2

你錯過了一個封閉的括號:

return self.points[0][1] + (x - self.points[0][0]) * float(self.points[1][1] - self.points[0][1]/(self.points[1][0] - self.points[0][0]) 

它看起來像你的意思是有一個)之後self.points[0][1]

0

您需要在此行右括號(在else前一個右):

return self.points[0][1] + (x - self.points[0][0]) * float(self.points[1][1] - self.points[0][1]/(self.points[1][0] - self.points[0][0]) 

你有3個開括號,但只有兩個收盤。

我不能告訴你確切的位置放置它,因爲這取決於你想要做什麼。然而,它最有可能將是:

return self.points[0][1] + (x - self.points[0][0]) * float(self.points[1][1] - self.points[0][1]/(self.points[1][0] - self.points[0][0])) 
#                                 here--^ 

或:

return self.points[0][1] + (x - self.points[0][0]) * float(self.points[1][1] - self.points[0][1])/(self.points[1][0] - self.points[0][0]) 
#                       here--^