注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

BeyondEgo

Welcome to Winsolider's yard! 超越自我,谁与争锋?

 
 
 

日志

 
 
关于我

本博为记事、畅聊、交友博客,邀你共同探讨人生、探讨成长,广交天下有志之士!愿与有相同兴趣爱好的你,共同学习、一起成长、收获喜悦!

网易考拉推荐

Python eval()函数:字符变代码  

2012-03-26 11:01:01|  分类: 程序员 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

 

#[Double Gold Star] Memoization is a way to make code run faster by saving
#previously computed results.  Instead of needing to recompute the value of an
#expression, a memoized computation first looks for the value in a cache of pre-
#computed values.

#Define a procedure, cached_execution(cache, code), that takes in two inputs: a
#cache, which is a Dictionary that maps strings representing Python expressions
#to their previously computed values, and code, a string that is a Python
#expression.  Your procedure should return the value of code, but should only
#evaluate code if it has not been previously evaluated.

def cached_execution(cache,code):
    if code in cache:
        return cache[code]
    c=eval(code)
    cache[code]=c   
    return c

#Here is an example showing the desired behavior of cached_execution:

def factorial(n):
    print("Running factorial")
    result = 1
    for i in range(2, n + 1):
        result = result * i
    return result

cache = {} # start cache as an empty dictionary
### first execution (should print out Running factorial and the result)
print(cached_execution(cache, 'factorial(50)'))                          

print("Second time:")
### second execution (should only print out the result)
print(cached_execution(cache, 'factorial(50)'))

PS:

终于找到你了!

  评论这张
 
阅读(1666)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017