memoization

“Caching” attributes of classes in Python

纵然是瞬间 提交于 2019-11-27 17:58:49
I'm writing a class in python and I have an attribute that will take a relatively long time to compute, so I only want to do it once . Also, it will not be needed by every instance of the class, so I don't want to do it by default in __init__ . I'm new to Python, but not to programming. I can come up with a way to do this pretty easily, but I've found over and over again that the 'Pythonic' way of doing something is often much simpler than what I come up with using my experience in other languages. Is there a 'right' way to do this in Python? Maxime R. Python ≥ 3.2 You should use both

Scala Memoization: How does this Scala memo work?

非 Y 不嫁゛ 提交于 2019-11-27 17:53:05
The following code is from Pathikrit's Dynamic Programming repository. I'm mystified by both its beauty and peculiarity. def subsetSum(s: List[Int], t: Int) = { type DP = Memo[(List[Int], Int), (Int, Int), Seq[Seq[Int]]] implicit def encode(key: (List[Int], Int)) = (key._1.length, key._2) lazy val f: DP = Memo { case (Nil, 0) => Seq(Nil) case (Nil, _) => Nil case (a :: as, x) => (f(as, x - a) map {_ :+ a}) ++ f(as, x) } f(s, t) } The type Memo is implemented in another file: case class Memo[I <% K, K, O](f: I => O) extends (I => O) { import collection.mutable.{Map => Dict} val cache = Dict

How can I memoize a method that may return true, false, or nil in Ruby?

故事扮演 提交于 2019-11-27 17:31:15
问题 Obviously ||= won't work def x? @x_query ||= expensive_way_to_calculate_x end because if it turns out to be false or nil , then expensive_way_to_calculate_x will get run over and over. Currently the best way I know is to put the value into an Array : def x? return @x_query.first if @x_query.is_a?(Array) @x_query = [expensive_way_to_calculate_x] @x_query.first end Is there a more conventional or efficient way of doing this? UPDATE I realized that I wanted to memoize nil in addition to false -

python resettable instance method memoization decorator

自闭症网瘾萝莉.ら 提交于 2019-11-27 16:32:01
问题 I'm attempting to build a decorator for an instance method of a class that will memoize the result. (This has been done a million times before) However, I'd like the option of being able to reset the memoized cache at any point (say, if something in the instance state changes, which might change the result of the method having nothing to do with its args). So, I attempted to build a decorator as a class instead of a function, so that I might have access to the cache as a class member. This

Memoizing Coin Change

岁酱吖の 提交于 2019-11-27 16:23:05
I want to convert my coin change function to memoized function to do that, I decided to use dictionary so that a key in my dict will be the coin and the value will be a list that contain all the coins that can change the "key" coin. what I did is: def change(a,kinds=(50,20,10,5,1)): if(a==0): return 1 if(a<0 or len(kinds)==0): return 0 return change(a-kinds[0],kinds)+change(a,kinds[1:]) def memoizeChange(f): cache={} def memo(a,kinds=(50,20,10,5,1)): if len(cache)>0 and kinds in cache[a]: return 1 else: if(f(a,kinds)==1): cache[a]=kinds // or maybe cache[a].append(..) return cache[a]+memo(a

Memoization of promise-based function

蓝咒 提交于 2019-11-27 16:10:21
How can I memoize a promise-based function? Would straightforward memoization of the function suffice? function foo() { return new Promise((resolve, reject) => { doSomethingAsync({ success: resolve, fail: reject }); }); }; Would this suffice? var fooMemoized = memoize(foo); Note: this question has been updated to remove the deferred anti-pattern. Bergi Yes, that will suffice. Promises are simple return values, which is their great benefit - in contrast to callbacks, where memoisation code would be horrible. You only might want to make sure that the memoized promise is uncancellable, if your

Two parameter memoization in Haskell

梦想与她 提交于 2019-11-27 14:43:39
问题 I'm trying to memoize the following function: gridwalk x y | x == 0 = 1 | y == 0 = 1 | otherwise = (gridwalk (x - 1) y) + (gridwalk x (y - 1)) Looking at this I came up with the following solution: gw :: (Int -> Int -> Int) -> Int -> Int -> Int gw f x y | x == 0 = 1 | y == 0 = 1 | otherwise = (f (x - 1) y) + (f x (y - 1)) gwlist :: [Int] gwlist = map (\i -> gw fastgw (i `mod` 20) (i `div` 20)) [0..] fastgw :: Int -> Int -> Int fastgw x y = gwlist !! (x + y * 20) Which I then can call like

Store the cache to a file functools.lru_cache in Python >= 3.2

╄→尐↘猪︶ㄣ 提交于 2019-11-27 14:35:18
问题 I'm using @functools.lru_cache in Python 3.3. I would like to save the cache to a file, in order to restore it when the program will be restarted. How could I do? Edit 1 Possible solution: We need to pickle any sort of callable Problem pickling __closure__ : _pickle.PicklingError: Can't pickle <class 'cell'>: attribute lookup builtins.cell failed If I try to restore the function without it, I get: TypeError: arg 5 (closure) must be tuple 回答1: You can't do what you want using lru_cache , since

Python - anyone have a memoizing decorator that can handle unhashable arguments?

一世执手 提交于 2019-11-27 11:49:18
I've been using the following memoizing decorator (from the great book Python Algorithms: Mastering Basic Algorithms in the Python Language ... love it, btw). def memo(func): cache = {} @ wraps(func) def wrap(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrap The problem with this decorator is that the dictionary-based cache means that all of my arguments must be hashable. Does anyone have an implementation (or a tweak to this one) that allows for unhashable arguments (e.g. dictionaries)? I know that the lack of a hash value means that the question of "is

Combine memoization and tail-recursion

笑着哭i 提交于 2019-11-27 11:34:47
Is it possible to combine memoization and tail-recursion somehow? I'm learning F# at the moment and understand both concepts but can't seem to combine them. Suppose I have the following memoize function (from Real-World Functional Programming ): let memoize f = let cache = new Dictionary<_, _>() (fun x -> match cache.TryGetValue(x) with | true, y -> y | _ -> let v = f(x) cache.Add(x, v) v) and the following factorial function: let rec factorial(x) = if (x = 0) then 1 else x * factorial(x - 1) Memoizing factorial isn't too difficult and making it tail-recursive isn't either: let rec