Search code examples
pythonpython-3.xpython-3.7

Issues with if statements within Lambdas Python3


I am currently writing some code to scale vector graphics, but I am having some issues writing the error handling code in Python, particularly in the line that sets scaled_points within scalePoints. The function takes a list of coordinates (as tuples), a viewport size, and a shrink factor, and returns a scaled set of coordinates.

I am trying to avoid division by zero by using if statements within the lambda, but under certain test cases it does not appear to work. For instance, scalePoints([(0.0,1.0)], 300, 10) causes division by zero to occur, but scalePoints([(0.0,0.0)], 300, 10) does not, and I'm not quite sure why this is.

def scalePoints(points, viewport_size, shrink_factor):
    min_x = findMinX(points)
    max_x = findMaxX(points)

    width = max_x - min_x

    scale = (width/viewport_size) * shrink_factor
    scaled_points = list(map(lambda point: (0.0 if point[0] == 0.0 else (point[0]/scale), 0.0 if point[1] == 0.0 else (point[1]/scale)),points))
    return scaled_points
def findMaxX(points):
    xs = list(map(lambda point: point[0], points))
    return max(xs)
def findMinX(points):
    xs = list(map(lambda point: point[0], points))
    return min(xs)

Solution

  • Comparing point[0] and/or point[1] against 0.0 won't protect you from dividing by zero, because those are the numerator, not the denominator.

    Try checking the denominator, scale, instead.

    scaled_points = list(map(lambda point: (0.0 if scale == 0.0 else (point[0]/scale), 0.0 if scale == 0.0 else (point[1]/scale)),points))