Python Functional Efficiency Efficiency

If I do this:

x=[(t,some_very_complex_computation(y)) for t in z]

Apparently some_very_complex_comput (y) is independent of t. Therefore, it should be evaluated only once. Is there a way to make Python aware of this, so it will not evaluate some_very_complex_comput (y) for each iteration?

Edit: I really want to do this on one line ...

+3
source share
7 answers

Usually you should follow the advice of San4ez and just use the temporary variable here. I continue to present a few methods that may be useful in certain circumstances:

In general, if you want to associate a name only for subexpression (usually for what you need a temporary variable), you can use lambda:

x = (lambda result=some_very_complex_computation(y): [(t, result) for t in z])()

:

x = zip(z, itertools.repeat(some_very_complex_computation(y)))

,

, Python, , some_very_complex_computation , . , , Haskell, .

"" : Memoization

some_very_complex_computation :

from functools import lru_cache

@lru_cache()
def some_very_complex_computation(y):
  # ...

Python 3. Python 2 :

from functools import wraps

def memoize(f):
  cache = {}
  @wraps(f)
  def memoized(*args):
    if args in cache:
      return cache[args]
    res = cache[args] = f(*args)
    return res
  return memoized

@memoize
some_very_complex_computation(x):
  # ...
+7

,

result = some_very_complex_computation(y)
x = [(t, result) for t in z]
+4

, , . , lambda:

x=[(t,s) for s in [some_very_complex_calculation(y)] for t in z]

, , , San4ez , (, , , ).

+3

@San4ez , , .

, . for :

result = [(t, result) for result in [some_very_complex_computation(y)] for t in z] 

, , :

result = some_very_complex_computation(y); x = [(t, result) for t in z] 
+2

:

memoization (.. some_very_complex_comput (y) , , , , dict

+1

TL; DR

    zip(z, [long_computation(y)] * len(z))

:

, , :

_cached_results = {}

def computation(v):
    if v in _cached_results:
        return _cached_results[v]
    # otherwise do the computation here...
    _cached_results[v] = result
    return result

.

- , ... :

>>> def func(v):
...     print 'executing func'
...     return v * 2
... 
>>> z = [1, 2, 3]
>>> zip(z, [func(10)] * len(z))
executing func
[(1, 20), (2, 20), (3, 20)]
+1

, , .

0

All Articles