39 ms·
Current solutions: >>> list(map(partial(pow, exp=3), range(10))) [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] >>> list(map(lambda base: pow(base, 3), rang
by raymondh 5y ago
Current solutions:
>>> list(map(partial(pow, exp=3), range(10)))
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
>>> list(map(lambda base: pow(base, 3), range(10)))
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
>>> [pow(base, 3) for base in range(10)]
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
Proposed solution:
list(map(bp.partial(pow)(bp._, 3), range(10))
ISTM the only time you come out a little ahead is if you know in advance that a function is going to be partialed (so you can decorate it), that you will need to partial arguments in other than a left to right fashion (otherwise a plain partial will suffice), that you won't use keyword arguments (the current partial works with keywords), and that you really dislike the lambda keyword (which neatly covers all cases from simple to complex without a new notation).
That said, this is a clever recipe. Kudos to the author for putting it together. I don't think it really rises to the level of "better" or "more intuitive", but it is an interesting experiment.
- cgrimm1994 5y agoI'm glad you like the recipe :-) What if you have a function "f" that takes like 10 arguments and you need to pass it to a function "g" that expects as input a function takes 8 arguments. @partial def f(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10): return "stuff" g(f(..., p4=1, p7=2)) # seems nicer than g(lambda p1, p2, p3, p5, p6, p8, p9, p10: f(p1, p2, p3, 1, p5, p6, 2, p8, p9, p10))
- wheelerof4te 5y agoFirst mistake, making a function with 10 parameters. We have data structures for that, if you need it. Just pass in a big struct/named tuple as one parameter. Bonus points if it is type hinted.
- d0mine 5y agoNit: List comprehension looks better for expressions (preferable over lambda+map)