loop, python, define a series of variables and functions - python

I am new to Python and have difficulties to understand how to use loop.
could anyone help me how to write below code in a loop/list, which will be much shorter?
def a1(self):
if aorb1 == 1:
return texta1
return textb1
def a2(self):
if aorb2 == 1:
return texta2
return textb2
def a3(self):
if aorb3 == 1:
return texta3
return textb3
Thanks a lot.

I can take a stab at what direction you are going and provide some level of guidance, but I suspect that I won't go the correct direction without more information.
First off, you don't need self as a parameter. That only applies to objects.
Next, you do need to provide the variables used within the function as parameters. It looks like you tried to use a and b without declaring them.
def a1(a, b)
if a == 1:
return texta
elif b == 1:
return textb
Be careful that you don't miss any cases. What if a = 0 and b = 0? Then this function would return None.
Finally, I'm not sure exactly what you are trying to do with the loop, but perhaps something like this?
# assign a and b values somewhere
a = 1
b = 0
# save the functions in a list
my_functions = [a1, a2, a3]
# execute each function with the parameters `a` and `b`
for f in my_functions:
result = f(a, b)
x.append(result)
This will result in a list containing the results of your function executions with parameters a and b. Would like to help more, but we need more information. Perhaps the above will stimulate that.

You could generate lambdas where you pass a and b, as follows:
my_funcs = []
for i in range(1,4):
func = lambda a, b: textas[i] if a == 1 or b == 1 else textbs[i]
my_funcs.append(func)
You can call such a function like this:
my_funcs[0](0,1) # this does the same as your function a1
I don't know what you want texta1 or textb1 to be. This could be stored in a dictionary, like I do in the example above.

Related

I need to write generate_count function returns the function which returns the value increased by 1 and you can send the start value of count into fun

I wrote the code which does the first part of task: it returns the count of calls of function
def counter():
val = [0]
def generate_count():
val[0] += 1
return val[0]
return generate_count
generate_count = counter()
print(generate_count())
But also I must be able to send start value of count into the func. As I know if u enter in ur function that u need to pass arguments then u are not be able to leave value blank. For example: If u write like this
def func1(n):
then you must pass one argument to make it work otherwise it wont work, so how to make it possible to work if u pass any arguments else if u don`t?
Use a default value:
def func1(n=0):
<code>
This function can be called with a parameter n, or it can be called without n. If you call the function like this:
func1()
The value of the parameter n will be set to 0, as you didn't specify a value.
It would probably make more sense to use a builtin generator for this case.
def counter(n=0):
while True:
n += 1
yield n
generate_count = counter(1)
print(next(generate_count)) # > 2

I think it's a basic question but I don't get why I get 0 in this function

a = 0
def add(number):
number += 1
return number
for i in range(20):
add(a)
print(a)
I'm wondering why I get 0 for the print(a) call in the last line.
I put 0 for the first loop of the add()function and it should return 1 and so on in the for loop.
What am I missing?
I think you're just missing assigning the return value of add() back to a. Without the assignment, a never changes because function arguments are passed by value, not reference.
a = 0
def add(number):
number += 1
return number
for i in range(20):
a = add(a)
print(a)
it seems you aren't actually changing the value of a, try changing your for loop to look something like this:
for i in range(20):
a = add(a)
To make use of the return keyword, make sure you understand that it sends back a value to the main program, treat it like another variable.
When you pass an int to a function, you're basically passing a copy of it. So your function adds 1 to a copy of a and returns it, but there's nothing there to catch the returned value.
When you pass a list or dict to a function, you're passing a reference to the original object, though. If you change it inside your function it changes thoughout your code:
a = 0
b = [0]
c = {"engelbert": 0}
def add(number, lst, dct):
number += 1
lst[0] += 1
dct["engelbert"] += 1
# No return statement:
# Function returns `None` by default
for i in range(20):
add(a, b, c)
print(a, b, c)
# 0 [20] {'engelbert': 20}

Is there a way to change the argument name of a nested function?

So the easiest way to illustrate my question is through an example. Let's say I want to write a function function(a=None,b=None,c=None), this function will only take two arguments at a time and the third one will be left blank. For any two arguments that one gives to the function it will return the missing one such that a+b=c. So for example function(a=5, c=15) would return 10 and for function(a = 5, b = 10) it would return 15. Now for the sake of the argument let's say that a could not be written as a function of b and c, or its simply too complicated to find a closed solution (this is clearly not the case here because to find a, I could simply say a = c-b). Anyway, if I was to write such a function I'd do something like this:
#import a root finder
from scipy.optimize import newton
def function(a= None, b= None, c = None):
#find the missing parameter:
vars = [a,b,c]
comp = vars.index(None)
if comp == 0:
def aux_fun(a):
return (a+b-c)
elif comp == 1:
def aux_fun(b):
return (a+b-c)
else:
def aux_fun(c):
return (a+b-c)
return newton(aux_fun, 0)
I have not found a solution to this other than writing 3 different functions and calling the correct one in newton. This works for this small example but if I have a bigger problem let's say with 100 variables writing 100 functions is not pretty.
My question is: is there any way such that I only have to write aux_fun once and change its parameter based on the missing parameter from function
Thanks a lot for your answers!
I haven't fully grasped what you are trying to do, but I don't think you quite understand how newton works.
optimize.newton is going to call your function with
func(x, a, b, c ...)
where x is a scalar or array of the size of the initial value, the x0. The other arguments are passed via the args tuple. This pattern of passing an iteration variable and args to the function is widely used in these scipy.optimize functions. I've answered a number of questions regarding these arguments.
newton(func, x0, args=(a,b,c))
These aren't keyword arguments.
Read and experiment with the examples in the docs. People often mess up the args tuple. And then explore a few small examples of your own before seriously trying to do this 'renaming'.
edit
This might work - I haven't tested it:
def function(a= None, b= None, c = None):
#find the missing parameter:
vars = [a,b,c]
comp = vars.index(None)
def aux_fun(x):
vars[comp] = x
a,b,c = vars
return (a+b-c)
return newton(aux_fun, 0)
What you want is impossible. Given a generic function f(a, b, c, d) = 0, there is no way to generically turn it into a set of functions a = f1(b, c, d), b = f2(a, c, d), etc. You are entering the realm of symbolic computation. You would need your code to understand trigonometry, algebra, calculus, exponentiation and logarithms.
Updating based on comments below.
So you want something like:
def aux_func(x):
vars[comp] = x
return f(*vars)

Use the result of the return of one function in another function [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 months ago.
I know there are several questions about this, I read but I could not understand. I'm trying to use the result of the return of one function in another:
def multiplication(a):
c = a*a
return c
def subtraction(c):
d = c - 2
return d
print(subtraction(c))
Output:
NameError: name 'c' is not defined
I know that there is a possibility of using global variables, but I have seen that this is not a good idea since the variables can change their value.
EDIT:
These two functions are just idiotic examples. I have two functions with words and I need to use the return of the first function in the second function. In case of this my idiotic example, I need the result of the first function (c) in the second function.
You are not calling your functions properly.
def multiplication(a):
c = a*a
return c
def subtraction(c):
d = c - 2
return d
# first store some value in a variable
a = 2
# then pass this variable to your multiplication function
# and store the return value
c = multiplication(a)
# then pass the returned value to your second function and print it
print(subtraction(c))
Does this makes things clearer?
def multiplication(a):
c = a*a
return c
def subtraction(c):
d = c - 2
return d
print(multiplication(5)) # 25
print(subtraction(5)) # 3
print(multiplication(subtraction(5))) # 9
print(subtraction(multiplication(5))) # 23
I think you're trying to do what's happing in the last print statement: first call the multiplication function, and then call the subtraction function on the result.
Note that the variable c in your multiplication function is an entirely different variable from the c in your subtraction function. So much so, that it may make things more clear to rename your variables, perhaps something like this:
def multiplication(a):
product = a * a
return product
def subtraction(a):
difference = a - 2
return difference
So why not use return value?
print(subtraction(multiplication(24)))
?
'c' is not declared outside the 'subtraction' function.
You need to give need to declare 'c' before printing.
Let's say you want 'c' to be 5, then:
c = 5
print(subtraction(c))
You have defined two functions which both return a number.
If you call subtraction(c) you will get the error you see, because there is no c.
If you define a c in scope of the print statmenet
c = 42
print(subtraction(c))
it will be ok.
Try thinking of it like this: each function takes a variable does things to it and returns a number.
e.g.
>>> multiplication(101)
10201
That this happened to be called c isnide the function isn't known outside the function (i.e scope).
You can save the number to a variable
>>> x = multiplication(101)
Then x remembers that value.
Or
>>> c = multiplication(101)
This is not the same c as you have inside the functions.
(And after the question edit):
Decide what value you want to call the first function with, for example 101:
>>> c = multiplication(101)
then use that return to call the next function:
>>>> subtraction(c)
Or just chain them togther:
subtraction( multiplication(101) )
To start the chain you will need to use a string, int or defined variable.
Otherwise you get name not defined errors.
Once a variable is used in a function it goes out of scope when the function ends.

Want to refer to variable in the outer function's scope from an inner function being returned

So I'm making a simple program that gets 2 functions(a and k) and one integer value(b), then it gets the formal parameter in the two functions(a and k) which is "x" and applies a condition x < b then based on the condition makes a function call, either a or b. But when I run the program it gives an error that x is not defined in the global frame. I want it to get "x" from the formal parameter assigned to the functions a and b and then get the condition based on that.
Here's my code
def square(x):
return x * x
def increment(x):
return x + 1
def piecewise(a, k, b):
if x<b:
return a
else:
return k
mak = piecewise(increment,square ,3 )
print(mak(1))
I guess you want to do something like this:
def piecewise(a, k, b):
def f(x):
if x < b:
return a(x)
else:
return k(x)
return f
However, I am not sure if it is a good practice. So, I leave my answer here to see the comments and learn if there is any problem with it.

Categories