Thursday, 2 February 2023

Pass in any variable while guaranteeing predefined relationship

I have a simple formula taking basic arithmetic calculations given several inputs.

a = 1
b = 2
c = a + b #3=1+2 
d = 4
e = c + d #7=3+4

graph of relationship

In theory, the relationships should always hold true. And I want to write a function that user can modify any variable and the rest will be auto updated (update priority has been predefined if there are more than one alternative eg. update the most right node first).

def f():
    #default state
    state = {'a':1, 'b':2, 'c':3, 'd':4, 'e':7}
    ...
    return state

f(a=0) == {'a':0, 'b':2, 'c':2, 'd':4, 'e':6}
f(c=4) == {'a':1, 'b':3, 'c':4, 'd':4, 'e':8}
f(b=2, c=4) == {'a':2, 'b':2, 'c':4, 'd':4, 'e':8}

graph of modified relationship for c=4

I tried to use **kwargs and *args to allow the user to pass in any variable but have to hard code the update logic based on which variable got modified. Any better ideas?

P.S.: this example is for demonstration purpose; the real problem involves much more variables and the mathematical relationship is also more difficult (logarithm, exponential, ..)



from Pass in any variable while guaranteeing predefined relationship

No comments:

Post a Comment