动态创建函数总和

时间:2018-02-05 14:24:14

标签: python-3.x function dynamic-programming factory

我无法接近程序中的必要元素:

给定形式的一组点(x,y,a)产生形式的高斯函数:

f(x,y)

......从每一点开始。然后生成一个函数,它是所有创建的子函数的总和。

问题

目前,我要做的是从每个点创建一个函数并将其附加到列表中。然后我创建一个新函数,它是这个函数列表中项的总和。这可以按预期工作,但我想要一种更有效的方法。

除了作为超级函数的表达式之外,我不使用子函数。所以我想知道是否可以跳过第一步,而是直接从一组任意大小的点创建超级函数。以下是预期结果的示例:

实施例

给定集:[point(2,1,4),point(3,2,1),point(1,4,3)]
制作:Ex1

给定集合:[point(4,2,1),point(3,5,6)]
制作:Ex2

注意:请记住,我调用的内容实际上只是列表。

2 个答案:

答案 0 :(得分:2)

from math import exp, pow

class AllPoint:
    def __init__(self, array):#give the set of points
        self.points = array

    def applyGaussianFunction(self, x, y): #for each point sum the gaussian function result
        if(len(self.points) == 0): #if there is no point launch an error
            raise AssertionError("no points in the array")
        allSum = 0
        for p in self.points: #doing the sum of every gaussian function
            allSum += p.gaussianFunction(x, y);
        return allSum

class Point: #create an object named point (the keywork self means the object in question #this)
    def __init__(self, x, y, a): #this object posseed three attributes (x, y, a) 
        self.x = x
        self.y = y
        self.a = a

    def gaussianFunction(self, x, y): #each point can apply the gaussian function on himself so each point can call her by doing ThePoint.gaussianFunction(x, y)
        return self.a * exp(-pow(x - self.x, 2)-pow(y - self.y, 2)) #the formula

p1 = Point(4, 2, 1)
p2 = Point(3, 5, 6)
points = AllPoint([p1, p2])
print(points.applyGaussianFunction(3, 4))

答案 1 :(得分:1)

from math import exp, pow
from collections import namedtuple

Point = namedtuple('Point', 'x y a')

def sum_function(x, y, points):
  # use list comprehension to loop over the points and calculate the gaussian, 
  # then use the sum function to compute the sum of the list elements
  return sum([p.a * exp(-pow(x - p.x, 2) - pow(y - p.y, 2)) for p in points])

p1 = Point(4,2,1)
p2 = Point(3,5,6)
a_certain_set_of_points = (p1, p2)

回答你关于如何避免两次引用某一组点的问题,你可以使用lambda:

a_certain_sum_function = lambda x,y : sum_function(x, y, a_certain_set_of_points)
print(a_certain_sum_function(1, 2))
PS:我会把这个答案作为对romph帖子的评论,但我似乎没有足够的代表来这样做:o