-1

I have a couple of functions defined like this (all parameters in a single array):

import numpy as np

def poly(x, params):
    val = 0.
    for i in range(len(params)):
        val += params[-1 - i]*(x**i)
    return val

a = 1.
b = 1.
c = 1.
params = [a, b, c]

Now I need to create the same function but without array as an argument of a function. I don't want to rewrite all my code, I need some new function for redefinition. The redefined function of my example should look like this:

def new_poly(x, a, b, c):
    #take all parameters and put them back in an array to make the rest of the code work
    params = [a, b, c]
    val = 0.
    for i in range(len(params)):
        val += params[-1 - i]*(x**i)
    return val

I will be grateful for any tips!

Rhoteb
  • 1
  • 2
    `def new_poly(x, *params)`? – Ch3steR May 26 '22 at 16:59
  • 3
    There isn’t really a need for the `new_poly` function. You can just call the original function like this: `poly(x, [a, b, c])` – Michael M. May 26 '22 at 16:59
  • Welcome to Stack Overflow. Please read [ask] and https://meta.stackoverflow.com/questions/284236, and *ask a question* - "I will be grateful for any tips" does not qualify, because this is *not a discussion forum* and we are looking for a *specific* question (so that other people who have that question can find the post with a search engine, and get a direct answer). – Karl Knechtel May 26 '22 at 17:00
  • The problem is I'm putting functions as arguments for scipy.optimize.curve_fit and the form `def poly(x, params)` is not valid. All parameters need to be called separately, like in new_poly. That's why I need to create a new functions – Rhoteb May 26 '22 at 17:29

1 Answers1

0

You can use *args:

def use_star_args(*args):
    params = [*args]
    print(params)

use_star_args(1, 2, 3)
Tomer Ariel
  • 1,397
  • 5
  • 9