Is there such thing as "apply" in python? - python

I wonder, is there a function in python -let's call it now apply- that does the following:
apply(f_1, 1) = f_1(1)
apply(f_2, (1, 2)) = f_1(1, 2)
...
apply(f_n, (1, 2,..., n)) = f_n(1, 2,..., n) # works with a tuple of proper length
Since it does exist in eg. A+ and Mathematica and it used to be really useful for me.
Cheers!

Python has language-level features for this, known as "argument unpacking", or just "splat".
# With positional arguments
args = (1, 2, 3)
f_1(*args)
# With keyword arguments
kwargs = {'first': 1, 'second': 2}
f_2(**kwargs)

You can use the * operator for the same effect:
f_1(*(1, 2)) = f_1(1, 2)
...
The expression following the * needn't be a tuple, it can be any expression that evaluates to a sequence.
Python also has a built-in apply function that does what you'd expect, but it's been obsolete in favor of the * operator since Python 2.3. If you need apply for some reason and want to avoid the taint of deprecation, it is trivial to implement one:
def my_apply(f, args):
return f(*args)

Yep, use the * operator on the list of arguments. For a practical example:
max(1, 2, 3, 4, 5) # normal invocation
=> 5
max(*[1, 2, 3, 4, 5]) # apply-like invocation
=> 5
Think of the second snippet as equivalent to apply(max, [1, 2, 3, 4, 5])

Related

How keywords inherit to default arguments

We know a partial function is an original function for particular argument values. Basic syntax of partial function is,
partial(func[, *args][, **keywords])
Now, let's assume a particular program.
from functools import partial
def power(a, b):
return a ** b
pw = partial(power, b=4)
print('Default keywords for pw :', pw.keywords)
print('Default arguments for pw :', pw.args)
print('Answer of pw is: ',pw(3))
# Output
# -------
# Default keywords for pw: {'b': 4}
# Default arguments for pw: ()
# Answer of pw is: 81
The output is correct and the above partial function i set keywords as b=4 and default agrs is (). Now, if I omit the keyword b and that place i put only 4. The scenario is changed to answer is 64.
partial(power, 4)
# Output
# -------
# Default keywords for pw: {}
# Default arguments for pw: (4,)
# Answer of pw is: 64
My question is why args and keywords get interchanged when I don't want to pass b since though in the first case I didn't pass a but the result was correct.
You are providing 4 as a positional argument, and those are applied strictly from left to right when calling the partial instance. That is, partial(f, 4) is roughly the equivalent of lambda x: pow(4, x). There is no way to define an equivalent of the function lambda x: pow(x, 4) with partial without using keyword arguments.
I think you got confused with the interplay of partial and positional and keyword argument here.
Here is the simple explanations: when keywords arg. are used in the call, the order in which the arguments are listed does NOT matter! Python matches by name, not
order. The caller must supply - spam, and eggs in the examples shown next, but they can be matched by position or by name - as you can see last 2 examples.
def func(spam, eggs, toast=0, ham=1): # first 2 required
print((spam, eggs, toast, ham))
func(1, 2) # (1, 2, 0, 1)
func(1, ham=2, eggs=0) # (1, 0, 0, 2)
# *****
#
print('------------------')
print('spam-lover, hate eggs: ')
func(spam=2, eggs=0) # (2, 0, 0, 1)
print()
print('love spam and eggs: ')
func(toast=1, eggs=4, spam=2) # (2, 4, 1, 1)
print('love spam/eggs and ham, want it toast too! ')
func(ham=6, eggs=4, spam=2, toast=1) # (2, 4, 1, 6)
func(1, 2, 3, 4) # (1, 2, 3, 4)
The form - name=value means different things in the call and the def!!!
a keyword in the call and
a default in the func. header.

Why does unpacking give results in tuple

I am learning arbitrary value parameter and reading stackoverflow this and this answers and other tutorials I already understood what *args and **kwargs do in python but I am facing some errors. I have two doubts, first one is:
If I run this code print(w) then I am getting this output:
def hi(*w):
print(w)
kl = 1, 2, 3, 4
hi(kl)
output:
((1, 2, 3, 4),)
but if I run this code with print(*w) then I am getting this output:
code:
def hi(*w):
print(*w)
kl = 1, 2, 3, 4
hi(kl)
output:
(1, 2, 3, 4)
My second doubt is:
je = {"a": 2, "b": 4, "c": 6, 4: 5}
for j in je:
print(*je)
output
b a 4 c
b a 4 c
b a 4 c
b a 4 c
What exactly is *je doing there? How is it working in iteration?
When you use * in declaration of the arguments def hi(*w):, it means that all the arguments will be compressed to the tuple, e.g.:
hi(kl, kl) # ((1, 2, 3, 4), (1, 2, 3, 4))
After when you use print(*w) * run unpack of your tuple.
je={"a":2,"b":4,"c":6,4:5}
for j in je:
print(*je)
In every iteration you use unpack of your dict (you use je and get the keys of your dict like [j for j in je])
https://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments
Your first case, it's because you're passing kl into the function as a tuple, not as arbitrary values. Hence, *w will expand into a single element tuple with kl as the first value.
You're essentially calling:
hi((1, 2, 3, 4))
However, what I suspect you want is
hi(1, 2, 3, 4)
# or in your case
hi(*kl)
When printing in python 3, print is a function, so again. When w is a tuple and you call it like:
print(w)
# you'll get the tuple printed:
# (1, 2, 3, 4)
However, again, you can call it with arguments like:
print(1, 2, 3, 4)
# or in your case
print(*w)
# 1 2 3 4
For your second part, look at it converted to a list first:
list({"a":2,"b":4,"c":6,4:5})
# ["b", "a", 4, "c"]
# Note, dictionaries are unordered and so the list could be in any order.
If you were to then pass that to print using the * expansion:
print("b", "a", 4, c)
# or in your case
print(*["b", "a", 4, "c"])
Just note, that the * does the default iteration for you. If you wanted some other values, use je.values() or je.items()

Confused about ** parameters in python function calls [duplicate]

This question already has answers here:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 9 years ago.
For reference I am referring to the answer in this post
The author of the answer gives the following code
def sum(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if neg:
s = -s
return s
s = sum(1, 2, 3, 4, 5) # returns 15
s = sum(1, 2, 3, 4, 5, neg=True) # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15
However when I run on mine I get the following error
NameError: global name 'neg' is not defined
Can anyone explain this. And in general, how does the function know when values ends and when options begins
if neg:
That line is buggy. It should be:
if options["neg"]:
How does the function know when values ends and when options begins?
Unnamed values go in *values. Keyword arguments go in **options.
You have made a small mistake. Change your code to the following and it should work. Just get the value of "neg" from the options dictionary, (values holds the unnamed arguments and options holds the keyword arguments)
>>> def sum(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
>>> s = sum(1, 2, 3, 4, 5, neg=True)
>>> s
-15
>>> sum(1, 2, 3, 4, 5)
15
>>> sum(1, 2, 3, 4, 5, neg=True)
-15
>>> sum(1, 2, 3, 4, 5, neg=False)
15
Although, as #glglgl pointed out, changing your code to the following consumes both the if statements into one.
>>> def sum(*values, **options):
s = 0
for i in values:
s = s + i
if options.get("neg", False):
s = -s
return s
How does get(...) work?
If the options dictionary doesn't have a key "neg", (as handled by your first if condition), then, get(...) returns the default value of False and s is not negated, and if options contains "neg", then it's value is returned, in which case, s is negated depending on the value in the dictionary.

How to convert list to tuple and search for max and min

I am currently learning python coding and I come across this qns on a learning site:
Create a function that takes a sequence of inputs (may be a list, a tuple, or just a bunch of inputs). The function should return the minimum and the maximum of the list.
This are some of the test values that are using:
minmax(5,4)
4,5
minmax(5,4,8,3,5,7,4)
3,8
minmax([5,4,6])
4,6
minmax(5.1,4.2,68.34,129.1,-90.3)
-90.3,129.1
And I had tried doing it this way but when the parameter is a list, I can't seems to convert it into a tuple and find the max and min.
Here is what I had tried:
def minmax(*a):
b = tuple(a)
minNum = min(b)
maxNum = max(b)
c = (minNum, maxNum)
return c
When a list is taken in, the return result is ([5, 4, 6], [5, 4, 6])
def minmax(*a):
if len(a) == 1: # Single (list, tuple, or scalar) argument
try:
return minmax(*a[0]) # Expansion of sequence elements, if possible
except TypeError: # Case of minmax(42)
pass # The general code below handles this directly
return (min(a), max(a))
>>> minmax(3, 5, 1, 10)
(1, 10)
>>> minmax([3, 5, 1, 10])
(1, 10)
>>> minmax((42, 123, -12))
(-12, 123)
>>> minmax(42)
42
This works in more cases than the built-in min() and max(), which do not work on a single scalar argument (min(42)).
>>> min(42)
TypeError: 'int' object is not iterable
It is however possible to write a simpler version that behaves like the built-in min() and max() (see my other answer, for instance).
This works by forcing min() to be given strictly more than 1 element, except in the special case of minmax(42), which calls min((42,)).
To be able to handle different ways of passing in arguments, you need to have some conditions to handle each case.
>>> def minmax(*a):
... if len(a) == 1 and hasattr(a[0], '__getitem__'):
... # handle a single sequence passed in
... return min(a[0]), max(a[0])
... # handle values passed in
... return min(a), max(a)
...
>>> minmax(5, 4)
(4, 5)
>>> minmax(5, 4, 8, 3, 5, 7, 4)
(3, 8)
>>> minmax([5, 4, 6])
(4, 6)
>>> minmax(5.1, 4.2, 68.34, 129.1, -90.3)
(-90.3, 129.1)
A simpler but slightly less powerful solution that mirrors my other solution is:
def minmax(*a):
if len(a) == 1: # Single (list or tuple) argument
return (min(a[0]), max(a[0]))
return minmax(a) # Single tuple argument given to minmax()
This version forces min() to be given a single (list or tuple) argument.
It behaves like the built-in min() and max(): min(42) and minmax(42) both raise an exception:
>>> minmax(3, 5, 1, 10)
(1, 10)
>>> minmax([3, 5, 1, 10])
(1, 10)
>>> minmax((42, 123, -12))
(-12, 123)
>>> minmax(42)
TypeError: 'int' object is not iterable
>>> min(42)
TypeError: 'int' object is not iterable

Why does unpacking a tuple cause a syntax error?

In Python, I wrote this:
bvar=mht.get_value()
temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
I'm trying to expand bvar to the function call as arguments.
But then it returns:
File "./unobsoluttreemodel.py", line 65
temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
^
SyntaxError: invalid syntax
What just happen? It should be correct right?
Update: this behavior was fixed in Python 3.5.0, see PEP-0448:
Unpacking is proposed to be allowed inside tuple, list, set, and dictionary displays:
*range(4), 4
# (0, 1, 2, 3, 4)
[*range(4), 4]
# [0, 1, 2, 3, 4]
{*range(4), 4}
# {0, 1, 2, 3, 4}
{'x': 1, **{'y': 2}}
# {'x': 1, 'y': 2}
If you want to pass the last argument as a tuple of (mnt, False, bvar[0], bvar[1], ...) you could use
temp = self.treemodel.insert(iter, 0, (mht,False)+tuple(bvar) )
The extended call syntax *b can only be used in calling functions, function arguments, and tuple unpacking on Python 3.x.
>>> def f(a, b, *c): print(a, b, c)
...
>>> x, *y = range(6)
>>> f(*y)
1 2 (3, 4, 5)
Tuple literal isn't in one of these cases, so it causes a syntax error.
>>> (1, *y)
File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target
Not it isn't right. Parameters expansion works only in function arguments, not inside tuples.
>>> def foo(a, b, c):
... print a, b, c
...
>>> data = (1, 2, 3)
>>> foo(*data)
1 2 3
>>> foo((*data,))
File "<stdin>", line 1
foo((*data,))
^
SyntaxError: invalid syntax
You appear to have an extra level of parentheses in there. Try:
temp=self.treemodel.insert(iter,0,mht,False,*bvar)
Your extra parentheses are trying to create a tuple using the * syntax, which is a syntax error.

Categories