根据条件的组合扩展行为

时间:2017-10-25 02:32:56

标签: python algebra

我在python中编写了一些大致接近以下内容的代码:

vals = [3, 4]
constraints = [5, 10]

def foo(val, constraint):
    return val <= constraint

def bar(x, y):
    # do stuff such as:
    print(x, y)

def baz(val):
    # transform val, such as by doing: 
    new_val = (val * 20 - 5) ** 2
    return new_val

bar(*vals)
if foo(vals[0], constraints[0]):
    bar(vals[0], baz(vals[1]))
if foo(vals[1], constraints[1]):
    bar(baz(vals[0]), vals[1])
if foo(vals[0], constraints[0]) and foo(vals[1], constraints[1]):
    bar(baz(vals[0]), baz(vals[1]))

我认识到这是一种代数关系,所以感觉应该有更简洁的方式在代码中表示这一点。

让我们说索引0上由True返回的fooA,而True在索引1上返回的fooBA为真时应用的操作为a,同样Bb。任何其他结果是_。要生成的值集将是:

  |   _    |    A   |    B   |
-----------------------------
_ |  x,  y |  x,  y |  x,  y |
  |        | ax,  y |  x, by |
-----------------------------
  |  x,  y |  x,  y |  x,  y |
A | ax,  y | ax,  y |  x, by |
  |        |        | ax, by |
-----------------------------
  |  x,  y |  x,  y |  x, y  |
B |  x, by | ax,  y |  x, by |
  |        | ax, by |        |

是否有一种简洁(最好是通用)的方式来生成这些值,以便以后可以map ped或迭代?

1 个答案:

答案 0 :(得分:0)

不可否认,当你说你想要一种简洁的方式在代码中表示这一点时,我不确定是什么意思。如果您想要概括这些功能,可以使用:

def foo(val, constraint):
    return val <= constraint

def bar(x, y):
    print x, y

def baz(val):
    return (val * 20 - 5) ** 2

def foobar(a, b)
    if a <= b:
        print a, b

def barbaz(a, b, c)
    if b <= c:
        print baz(a), b

def bazfoo(a, b, c, d)
    if a <= b and c <= d:
        print baz(a), baz(c)

vals = [3, 4]
constraints = [5, 10]

bar(*vals)

foobar(vals[0], constraints[0])
barbaz(vals[0], vals[1], constraints[1])
bazfoo(vals[0], constraints[0], vals[1], constraints[1])