2

I would like to define a function that uses another function with a variable number of parameters passed as parameter. The problem is to get the parameters in (1) and pass them to the call in (2):

def f1(x):
  return x
def f2(x,a):
  return x+a  
def f3(x,a,b):
  return b*x+a

def genStr(x0,x1, n, f, *params):  # <----------------- (1)
  out = ''
  dx = (x1-x0)/(n-1)
  x = x0
  out += r'\draw[thick] '
  for k in range(0,n):
    if k!=0:
      out += r' -- '
    out += '({:.4f},{:.4f})'.format(x,f(x,params))  # <------- (2)
    x += dx
  out += r';'
  return out

print(genStr(0, 2, 3, f1))
print(genStr(0, 2, 3, f2, 0.1))
print(genStr(0, 2, 3, f3, 2, 0.3))

1 Answer 1

2

You need to unpack the params list:

out += '({:.4f},{:.4f})'.format(x,f(x, *params ))  # * == splat operator, unpacks list

to get

\draw[thick] (0.0000,0.0000) -- (1.0000,1.0000) -- (2.0000,2.0000);
\draw[thick] (0.0000,0.1000) -- (1.0000,1.1000) -- (2.0000,2.1000);
\draw[thick] (0.0000,2.0000) -- (1.0000,2.3000) -- (2.0000,2.6000);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.