Program based on functions in Python - python

def add_sub(x,y):
d=x+y
e=x-y
return d,e
result=add_sub(7,6)
print(result)
The output for this function is (13,1), but i need output as mentioned below:
13
1

It needs to be like this:
def add_sub(x,y):
d=x+y
e=x-y
return d,e
result=add_sub(7,6)
for val in result:
print(val)
Since the result is returned on the tuple, tuple prints on that small braces.
Also, you can do this:
def add_sub(x,y):
d=x+y
e=x-y
return d,e
result=add_sub(7,6)
print("\n".join(map(str, result)))

When your function returns an iterable (a tuple in your case), and you know how many elements it will have, you can unpack it very easily:
def add_sub(x, y):
d = x + y
e = x - y
return d, e
result_add, result_sub = add_sub(7,6)
print(result_add)
# 13
print(result_sub)
# 1

Related

How to use one output of a function and store a second one=

So I have a function which outputs 2 values:
def example(a, b):
c = math.floor(a / b)
a = a%b
return (c, a)
I want to use this function this way:
print("text: ", c)
How can I use the function and print c, but store x for later?
Your function will return a tuple containing the two values. You can assign the result of calling your function to a variable.
Note,
that the parentheses are not required in your return statement.
you can replace math.floor(a / b) with a // b which will also do a floor division.
An example is shown below where the result of calling the function is unpacked into two variables, c and a.
def example(a, b):
c = a // b
a = a % b
return c, a
c, a = example(6, 3)
print("text:", c)
Alternatively, you can also store the result in a single variable that references your tuple as follows:
data = example(6, 3)
print("text:", data[0])
First, you need to call the function and assign its return values to some variables:
x, y = example(42, 5)
Then you can print the results:
print(x)
print(y)
You can even skip the variable assignment if you wish so
print("text:", example(a, b)[0])
but it's ugly

Can a current generator value interact with the value generated before it?

I'm aware yield generates a value on the fly, by my understanding this means it doesn't keep the value in the memory, and therefore the current value shouldn't be able to interact with the last values.
But I just want to be sure that's the case, could someone confirm if it's possible or not?
I'm going to use 5 as the value in number.
Example without generator:
def factorial(number):
result = number
if number <= 1:
return 1
else:
for x in reversed(range(1, number)): # (4,1) reversed
result *= x # 5*4*3*2*1
return result # returns 120
Is it possible to do the same thing by using the yield function? how?
Thank you
Generators can be stateful:
def fibs():
a, b = 1, 1
while True:
yield b
a, b = b, a + b
g = fibs()
for i in range(10):
print next(g)
Here the state is in the local variables. They are kept alive while the iterator generated by the generator is alive.
EDIT. I'm blind it was a factorial
def factorials():
i = 1
a = 1
while True:
yield a
i+=1
a*=i
or if you need a function not a stream of them then here's a one liner
print reduce(lambda a, b: a*b, (range(1, 10+1)))

List defining the list of variable of function in Python

I want to have a function foo which outputs another function, whose list of variables depends on an input list.
Precisely:
Suppose func is a function with the free variable t and three parameters A,gamma,x
Example: func = lambda t,A,gamma,x: Somefunction
I want to define a function foo, which takes as input a list and outputs another function. The output function is a sum of func's, where each func summand has his parameters independent from each other.
Depending on the input list the variables of the outputs changes in the following:
If the entry of the list is 'None' then the output function 'gains' a variable and if the entry of the list is a float it 'fixes' the parameter.
Example:
li=[None,None,0.1]
g=foo(li)
gives the same output as
g = lambda t,A,gamma: func(t,A,gamma,0.1)
or
li=[None,None,0.1,None,0.2,0.3]
g=foo(li)
gives the same output as
g = lambda t,A1,gamma1,A2:func(t,A,gamma,0.1)+func(t,A2,0.2,0.3)
Note: the order in the list is relevant and this behaviour is wanted.
I don't have any clue on how to do that...
I first tried to build a string, which depends on the inout list and then to execute it, but this is surely not the way.
First, partition the parameters from li into chunks. Then use an iterator to either get the next from the function parameters *args, if the value in that chunk is None, or the provided value from the parameters chunk.
def foo(li, func, num_params):
chunks = (li[i:i+num_params] for i in range(0, len(li), num_params))
def function(t, *args):
result = 0
iter_args = iter(args)
for chunk in chunks:
actual_params = [next(iter_args) if x is None else x for x in chunk]
result += func(t, *actual_params)
return result
return function
Example:
def f(t, a, b, c):
print t, a, b, c
return a + b + c
func = foo([1,2,None,4,None,6], f, 3)
print func("foo", 3, 5)
Output:
foo 1 2 3 # from first call to f
foo 4 5 6 # from second call to f
21 # result of func

python: How do I return value without bracket?

I am new to python and I am trying to figure out how to return a value without bracket.
Assume I have following function below.
def function(n):
a = 1
b = 2
return a - b, a + b
print function(n)
this prints out
(-1, 3)
But I want this function to print out
-1 3
You're returning a tuple from your function. So, receive it as two variables, then print each:
x, y = function(n)
print x, y
Or receive it as one variable, then print its items:
x = function(n)
print x[0], x[1]
Finally, since the return value is a sequence, you can join it, but you have to convert each item to a string first since they're integers:
print " ".join(map(str, function(x)))
If you are using Python 3, or using from __future__ import print_function, then print is a function, and you can use unpacking to turn your function's return value into multiple arguments:
print(*function(x))

Grid search function in Python

I am trying to write a parameter search function to loop over one of the parameters and repeatedly call a function with all other parameters the same, other than the one I am searching over. Here is some sample code:
def worker1(a, b, c):
return a + b + c
def worker2(d, e, f):
return d * e * f
def search(model, params):
res = []
# Loop over one of the parameters and repeatedly append to res
if model == 1:
res.append(worker1(**params))
elif model == 2:
res.append(worker2(**params))
return res
params = dict(a=1, b=2, c=3)
print search(1, params)
I have two workers and they are called depending on the value of the model flag I pass to search(). The problem I am trying to solve here is to write a loop (commented in the code) over the if statements to repeatedly call say worker1 by varying only one of the parameters. I want my code to be flexible - sometimes I want to loop through a and keep b and c the same, but sometimes I want to loop through b and keeping a and c the same.
I'm open whatever solution suggested, but I think I would be specifying the search parameters in the params dictionary. E.g. To loop a over 1,2,3,4, I would say:
`params = dict(a=[1,2,3,4], b=2, c=3)`
Also it would be nice if I don't have to modify the code for worker1 and worker2.
Thank you!
You could perhaps use itertools.product to call your workers with all combinations of params:
http://docs.python.org/2/library/itertools.html#itertools.product
eg
from itertools import product
def worker1(a, b, c):
return a + b + c
def worker2(d, e, f):
return d * e * f
def search(model, *params):
res = []
# Loop over one of the parameters and repeatedly append to res
for current_params in product(*params):
if model == 1:
res.append(worker1(*current_params))
elif model == 2:
res.append(worker2(*current_params))
return res
print search(1, [1,2,3,4], [2], [3])
# more complicated combinations are possible:
print search(1, [1,2,3,4], [2,7,9], [3,13,23,43])
I've avoided using keyword arguments as your worker functions take differently-named args so it wouldn't make much sense.
I'm assuming your worker functions don't actually look like the ones above as if they did you could further simplify the code using the builtin sum and reduce functions.
I am not sure if I understood the problem. Check if this is what you want (omitted the model parameter):
>>> def worker1(a, b, c):
return a + b + c
>>> def search(params):
params = params.values()
var_param = filter(lambda p: type(p) == list, params)[0]
other_params = filter(lambda p: p != var_param, params)
return [worker1(x, *other_params) for x in var_param]
>>> search({'a':2, 'b':[3,4,5], 'c':3})
[8, 9, 10]
Assuming:
arguments of worker1() are commutative (order does not matter).
variable parameter is a list
other parameters are single values.
In the above sample b is the variable parameter which you want to loop over
Update:
In case order of the arguments of the function worker1 is to be preserved:
def search(params):
params = params.items()
var_param = filter(lambda t: type(t[1]) == list, params)[0]
other_params = filter(lambda t: t != var_param, params)
var_param_key = var_param[0]
var_param_values = var_param[1]
return [worker1(**dict([(var_param_key, x)] + other_params)) for x in var_param_values]

Categories