Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am writing a code with the purpose of calculating a math function (given as an input) and calculate it with different values of x (without defining the x).
Example: input: y=log(2x) and i have to calculate for x=3,5,8
With the math module is quite easy to calculate the value of y given x but i can't find a solution to keep the x as variable and then calculate y depending on the change of x.
Since the moment that i can't write the function as a string i tried to define a new function
Example: def function(f, x)
So i just needed to input function(f=math.log(2x),x) but the problem is still there because when i recall the function changing the x (Example : function(f,x=5)) i don't have the f defined anymore.
So briefly, how i can make the functions of the math module dipendent from x?
You simply need to define a new function.
def example(x):
return math.log(2 * x)
Then you can call the function using the usual syntax
example(x)
As correctly noted in the comments, you can also define this function using anonymous syntax
example = lambda x: math.log(2 * x)
example(x)
Although this sort of defeats the purpose of anonymous functions if you're planning on giving the function a name anyway.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
This actually concerns with solving the discharge equation
Q= 1/nAR^(2/3)*S^(1/2)
where in instead of depth 'y' discharge 'Q' will be known and the depth would be found out by taking an initial approximation in the conventional way.
What I want is to develop a code in python that would solve for depth 'y' iteratively when given an initial approximation.
SymPy can easily solve this with the nsolve function:
>>> from sympy.abc import y
>>> eq = y - (5.172*(10+4.472*y)**0.4)/(10+2*y)
>>> from sympy import nsolve
>>> nsolve(eq, 1)
1.24179016236282
Python isn't great for CPU intensive operations like this. Approximating with pure Python with iterative method probably won't work. If the solution is guaranteed to be integer and you know the upper, lower bound of it, then you can use binary search. but for real number approximation it's pointless to do it with pure python.
Fortunately there are some libraries for this.
Here's a one-liner example:
import scipy.optimize as opt
sol=opt.fsolve(lambda y:(5.172*(10+4.472*y)**0.4)/(10+2*y)-y , 0)
print(sol)
# prints [1.24179016]
# this solves the equation of (function =0)
# note that the second argument '0' doesn't mean the target value
# target value is always 0. so you need to make a (equation)=0 form
# 2nd argument means initial estimated value,
# so it doesn't matter whether you put 0 or 1 or 100 there.
# you can give a function that returns multiple equations as the first
# argument to solve multi variable equations
You have to install scipy library. (using pip)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a function in Python, and in that same function i have multiple if statements. Lets say i want to return a value from my function. I create a local variable and change it in if statements. Problem is i need it to be defined in function so it works in every if statement, but unlike in C i cant use int a, b, c; but instead i have to give them a value. Problem is that value is going to be recognized if none of the if statements are true.
One clear solution is to take in global values as parameters of the function but i dont want to do that because i dont need their value i only want to change it.
velocity = 5
distance = 6
def calc(distance):
# i would need to say velocity = 5 here
distance + velocity # this does nothing but uses velocity so code cant run
if distance < 7 : # without defining velocity first (in first comment)
velocity = 6
elif distance < 10:
velocity = 7
return velocity
If you really don't want velocity to be a parameter of the function then build an object that has velocity as member variable and calc as method.
When writing Python functions, it is a good idea to strive to follow the following design principles, which come from functional programming.
A function's output should only depend on its inputs. That means that everything that influences the result should be a parameter of the function. This is generally easy to do, and makes the function self-documenting. When you write def foo(x, y, z), it is immediately obvious that the result depends on x, y and z.
A function preferably should only return its output. So it should not use global to modify variables outside of its scope, nor should it modify mutable arguments. (This cannot always be achieved in practice, but it is good to strive for.)
The main advantage is that such functions can be tested and debugged apart from the rest of the application, making those tasks much easier.
In this case,
def calc(distance)
should be:
def calc(distance, velocity)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am new on Python.
I want to create a function with two vectors inside. I tried like this
def twovectors((velocity1,length1),(velocity2,length2)):
but I have a message error like
SyntaxError: invalid syntax.
Please, need help.
You cannot put tuple in the function definition as a parameter. Check Multiple Function Arguments or 8.6. Function definitions in the Python language reference.
Try something like this this:
def twovectors(vector1, vector2):
velocity1, length1 = vector1
velocity2, length2 = vector2
# Other code...
I used tuple unpacking to expand provided tuple arguments.
You write functions in python in this way :
def twovectors(velocity1, velocity2):
# You can get the length of those vectors after you get inside the function
len1, len2 = len(velocity1), len(velocity2)
// Your code here
return whateveryouwantto
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have seen other people ask a question but the only answers I have seen simply explain that python doesn't have the same concept of pass by reference vs pass by value as languages like C do.
for example
x=[0]
def foo(x):
x[0] += 1
In the past, I have been using this work around but it seems very un-pythonic so I'm wondering if there is a better way to do this.
let's assume for what ever reason returning values won't work, like in the case where this code runs on a separate thread.
Some python objects are immutable (tuple, int, float, str, etc). As you have noted, you cannot modify these in-place.
The best workaround is to not try to fake passing by reference, instead you should assign the result. This is both easier to read and less error prone.
In your case, you could call:
x = 0
def f(x):
return x + 1
x = f(x)
If you truly need to fake passing by reference (and I don't see why you would need that), your solution works just fine, but keep in mind that you do not actually modify the object.
x = 0
x_list = [x]
print(id(x_list[0])) # 1844716176
def f(x_list):
x_list[0] += 1
f(x_list)
print(x) # 0, not modified
print(id(x_list[0])) # 1844716208
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm looking for a resource that will help me turn my python function definitions into professional quality functions.
For example, my current python definitions have the following form:
def foo(arg1,arg2,arg3=some_val,arg4=some_other_val):
""" Do something with the args """
# Create data using args
if arg3 == this_val:
return dataset_1, dataset_2
else :
return dataset_1, dataset_2, dataset_3
I would like for a way to return the data I'm interested in based on what return data I ask for.
For example, I could say:
ds_1, ds_2, ds_3 = foo(arg1,arg2)
or
ds_1, ds_2 = foo(arg1,arg2,arg3=only_two_datasets_bool)
How do I make it so the function doesn't need the optional argument to know I only want two datasets?
This is analogous to say matplotlib constructors where one can say:
n = plt.hist(data)
where n is the histogram but one can also do
n, bins = plt.hist(data)
and the hist function knows to return those two values with the same input of data (ie no optional arguments stating it should return bins).
While it may seem clunky and inelegant, you could unpack three variables and only use two of them if desired:
def foo(arg1, arg2):
return (arg1,arg2,3)
a, b, _ = asd(1,2)
print a, b # will print "1 2"
While the _ does not mean "unused variable" in python as it does in many other languages, many (or perhaps most) will recognize it as such. Even languages who don't offer explicit support for it, like Lua, encourage the use of _ as a placeholder variable due to conventions.
Use it in such a way that it is clear what the _ means though, as it in python shell contains the value of the previously evaluated expression:
>>> 1+2
3
>>> _+3
6
>>>