Python: maximization of function - python

Suppose I have the following simple function and inputs:
dates = pd.date_range('20170101',periods=20)
a1 = np.ones(3)
b1 = pd.DataFrame(np.random.randint(10,size=(20,3)),index=dates,columns=['foo','bar','see'])
def test_func(a,b):
c = (a*b).sum(axis=1)
d = c.std()*np.sqrt(3)
e = c.mean()/d
return -np.array(e)
I would like to solve this function for a that minimizes the output (maximizes e).
scipy.optimize.fmin(test_func,a1,args=(b1))
But this throws a type error
TypeError: test_func() takes 2 positional arguments but 4 were given
My quesiton is i) is this a good way to solve for the max of such a function and ii) what the devil is the problem?

You are missing a comma after the b1 in the extra argument:
scipy.optimize.fmin(test_func,a1,args=(b1,))
seems to work.

Related

Fibonacci Measurement Algorithm implementation: missing 1 required positional argument: 'p'

I've implemented a fibonacci Measurement algorithm with 2 parameter n and p.
I got this issue,
TypeError Traceback (most recent call last)
<ipython-input-19-295638b26e62> in <module>
2 N = 10
3 # [F(n,p) for n in range(N)]
----> 4 print(F(10,1))
<ipython-input-12-fda62c8ec9a6> in F(n, p)
6 elif n <= p+1:
7 return n
----> 8 return F(n-1) + F(n-p-1)
TypeError: F() missing 1 required positional argument: 'p'
I have input 2 parameters n =10, p = 1, but still having this problem "missing 1 required argument". Does anyone know why and solution for this or any suggestion would be appreciated!
There could be two potential issues.
You're calling a function, F, that doesn't seem to be defined in the snippet you've attached. You might want to change it to fibonacci_of if it is supposed to call itself recursively. In addition, since the fibonacci_of accepts two parameters, you would need to call it with two arguments
If F is already defined elsewhere, it is supposed to accept more than one argument. You could check its function definition and see the parameter requirements. See attached examples.
def square(a): # Requires single parameter.
return a ** 2
def add(a, b): # Requires two parameters.
return a + b

Error in Python: missing 1 required positional argument

I'm not so good with python and I keep getting this error:
TypeError: demand_curve() missing 1 required positional argument: 'pb'
And this is my code:
P,c,Q,y,pb,N,X,pf,t=sp.symbols('P c Q y pb N X pf t')
def demand_curve(c,Q,y,pb):
demand = (c.log(Q)-(-4.507+(0.841*y)+(0.2775*pb)))/(-0.397)
return demand
Q_num = np.linspace(0,100,100)
fig,ax=plt.subplots()
ax.set_ylabel('P')
ax.set_xlabel('E')
ax.plot(demand_curve(Q_num, 50, 2), Q_num,label='E (a=100,b=2)')
#legend:
ax.legend(loc='upper right', frameon=False)
ax.set(xlim=(0,100))
ax.set(ylim=(0,60))
I don't really understand what is the problem, can someone help me?
When you declare your function you do this :
def demand_curve(c,Q,y,pb):
...
So you have four parameters c, Q, y and pb, later in the code you call it using :
demand_curve(Q_num, 50, 2)
So in the way you call it you have
c = Q_num
Q = 50
y = 2
pb = Nothing at all
And python don't like this so you should provide and additional value when you call this function or provide a default value for the last parameter for example :
def demand_curve(c,Q,y,pb = "a default value"):
...
You are not passing all the arguments value when you call you function "demand_curve". Your function "demand_curve(c,Q,y,pb)" required 4 positional arguments but you give only 3 at "demand_curve(Q_num, 50, 2)".

Optional arguments in nested functions in Python

Is it possible for one function to take as an argument the name of one of the optional arguments of a second function then call the second function with the optional argument set to the value of some variable in the first function?
Code (that obviously doesn't work)
def foo(a=1,b=2,c=3):
d = a + b + c
return d
def bar(variable):
z = get_user_input()
e = foo(variable = z)
return e
print(bar(a))
The desired result is for bar to call foo(a=z) and print whatever z+2+3 is. Of course Python doesn't know what (a) is here. My guess is that I can somehow reference the list of arguments of foo() , but I am stumped as to how you might do that.
Maybe try the code snippet below
def foo(a=1,b=2,c=3):
d = a + b + c
return d
def bar(variable: str):
z = int(input())
e = foo(**{variable: z})
return e
# variable name should be defined as string
print(bar("a"))
The ** parses all arbitrary arguments on dict, in this case is a. Be careful tho, as if passing wrong variable name (differ from a, b or c) will result raising error.

What am I doing wrong in defining my function to get the error "numpy.ndarray" not callable?

This is my code:
def lsf2(x,y):
N = 100
A = (sum(x)*sum(y))/(sum(x)*(1-n))
B = (sum(y)-N*A)/sum(x)
delta = N*(sum(x**2)*sum(y))- sum(x)*sum(x*y)
sigy = (sum(y-A-B*x)**2/(N-2))**0.5
siga = sigy(sum(x)**2)/delta
sigb = sigy*(N/delta)**0.5
return A, B, sigy, siga, sigb
A, B, sigy, siga, sigb = lsf2(xdata, ydata)
print(A, B, sigy, siga, sigb)
The error I get is this:
----> 7 siga = sigy(sum(x)**2)/delta
TypeError: 'numpy.ndarray' object is not callable
You have:
sigy = (sum(y-A-B*x)**2/(N-2))**0.5
siga = sigy(sum(x)**2)/delta
sigy is a numpy array. When you type sigy(sum(x)**2)/delta you try to pass sum(x)**2 as input as if sigy was a function but it is not.
Maybe you need:
siga = sigy*(sum(x)**2)/delta # multiplication
or
siga = sigy**(sum(x)**2)/delta # power
The error is telling you that you are trying to call a function with sigy(...) but sigy is an array not a function. Based on the line following the one with the error, I think you are missing a *:
siga = sigy*(sum(x)**2)/delta
^ here
In math, we can write something like x(a+b) and we assume that the value of x is multiplied by the result inside the parentheses. In Python, this same syntax means to pass the value inside the parentheses to the function named x. You cannot leave out the multiplication operator in a Python program.
sigy is a numpy array, not a function. In the line siga = sigy(sum(x)**2)/delta, the sigy() is trying to call a function with the name sigy and argument sum(x)**2. If you are trying to index sigy you need to use [] like sigy[index].

Python function multiple arguments without calling function twice

I am trying to make a program that can do my algebra formulas. This is my code
{
k = 3
k2 = 20
def algebra(number):
print(5*number-10)
algebra(k)
}
I tried to do k2 and k at the same time like this
algebra(k,k2)
How can I make this work?
i hope this useful for you :
k = 3
k2 = 20
def algebra(*numbers):
for number in numbers:
print(5*number-10)
algebra(k,k2,k2)
output :
5
90
90
You could use args in your function, allowing you to call a function with multiple parameters. Your example would then become:
def algebra(*args):
for arg in args:
print(5*arg-10)
algebra(5, 10)
>> 15
>> 40
It seems like what you want is to call algebra on some variable number of k augments. There are a few ways to do this (map would likely be the most appropriate, but since you're just learning, I'll keep it simpler). One simple way is to have your function take in and return a list.
So you'd have somerh like
a = [k,k2]
And then in your algebra function, take a as an argument and iterate over its elements using a for loop like so:
For elem in a:
a[elem] = 5 * elem - 10
return a
And then print out the list that is returned in your main function

Categories