简体   繁体   English

记忆使用/缓存存储

[英]Memoization Usage/Cache Storing

I am writing a program that calculates the Pascal Identity of two variables, hard coded into the program, as I am new into Python and trying out caching and memoization. 我正在编写一个程序,该程序计算两个变量的Pascal Identity,并将其硬编码到程序中,因为我是Python的新手,并尝试了缓存和备注。 Here is what I have so far: 这是我到目前为止的内容:

counter = 0

call_cacheK = {}
   def callTest(n, k):
   global counter

   if n in call_cacheK:
       return call_cacheK[n]  
   if k == 0:
       return 1
   elif k == n:
       return 1 
   elif (1 <= k) and (k <= (n-1)):
       counter += 1
       #call_cacheK[n] = result
       result = ((callTest(n-1, k) + callTest(n-1, k-1)))
   print(result)
   return result

callTest(20, 11)
#167,960

My function will output the final real answer with what it has now, but with a lot of outputted answers. 我的函数将输出最终的实际答案,包括现在的答案,但输出的答案很多。 I cannot seem to get how to properly store the values to be used in the cache. 我似乎无法获得如何正确存储要在缓存中使用的值的方法。

How do I properly use call_cacheK to store the result values I have already used? 如何正确使用call_cacheK存储已经使用的result值?

Thank you. 谢谢。

Lets see. 让我们来看看。 First, you have a function of two variables, but store result in cache only by one parameter. 首先,您具有两个变量的功能,但是仅通过一个参数将结果存储在缓存中。 So callTest(20, 11) , callTest(20, 10) , callTest(20, 9) will have one result in your cache. 因此, callTest(20, 11)callTest(20, 10) callTest(20, 11)callTest(20, 10) callTest(20, 9)在您的缓存中将有一个结果。 Lets rewrite your function a little: 让我们稍微重写一下函数:

call_cacheK = {}

def callTest(n, k):
    if (n, k) in call_cacheK:
        return call_cacheK[(n, k)]  
    if k == 0:
        return 1
    elif k == n:
        return 1 
    elif (1 <= k) and (k <= (n-1)):
        result = ((callTest(n-1, k) + callTest(n-1, k-1)))
        call_cacheK[(n, k)] = result
    print(result)
    return result

Yes there is no counter variable because I didn't realize why do you need it :) 是的,没有计数器变量,因为我不知道您为什么需要它:)

Also, as far as I can judge by the use of print(result) , you probably use the Python3.x. 另外,据我可以通过使用print(result)判断,您可能使用了Python3.x。 If so, you can use standard cache implementing : 如果是这样,您可以使用标准的缓存实现

from functools import lru_cache

@lru_cache(maxsize=None)
def callTest2(n, k):  
    if k == 0:
        return 1
    elif k == n:
        return 1 
    elif (1 <= k) and (k <= (n-1)):
        result = ((callTest2(n-1, k) + callTest2(n-1, k-1)))
    print(result)
    return result

Good luck! 祝好运! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM