Euler_problem_14 for python(problem e)

网友投稿 196 2022-08-30


Euler_problem_14 for python(problem e)

Euler 14的不同解法 ----所涉及的知识 1. yield 2.BF 3. decorator 4.cache 5.等等

def euler_problem_14():

"""

最直接粗暴的解法:就是直接如下所示了

""" max_count = 1 max_value = 1 for i in xrange(100101, 1, -1): this_cycle_count = 1 status = i while status > 1: if status % 2 == 0: status /= 2 else: status = status * 3 + 1 this_cycle_count += 1 this_cycle_count += 1 if this_cycle_count > max_count: max_value = i (this_cycle_count, max_count) = (max_count, this_cycle_count) print("value: %s terms: %s" % (max_value, max_count))def euler_problem_14_1(): """ solve this large number using a simple cache to return the numberof terms from we already know """ max_count = 1 max_value = 1 sequence_cache_1 = dict() for i in xrange(1, 1000): status = i this_cycle_count = 0 while status > 1: try: this_cycle_count += sequence_cache_1[status] - 1 break except KeyError: pass if status % 2 == 0: # even status /= 2 else: # odd status = status * 3 + 1 this_cycle_count += 1 this_cycle_count += 1 sequence_cache_1[i] = this_cycle_count if this_cycle_count > max_count: max_count = this_cycle_count max_value = i print("value: %s term: %s" % (max_value, max_count))SEQUENCE_CACHE = dict()def cache_euler_14(func): def kicker(value, status=None, n=None): try: SEQUENCE_CACHE[value] = n - 1 + SEQUENCE_CACHE[status] return SEQUENCE_CACHE[value] except (KeyError, TypeError): pass if n is None: result = func(value, status) else: result = func(value, status, n) if status <= 1: SEQUENCE_CACHE[value] = result return result return kicker@cache_euler_14def euler_problem_14_2(value, status=None, n=1): """ 通过decorator 来进行性能的提升 装饰器 cache_euler14 """ if status is None: status = value if status <= 1: return n if status % 2 == 0: # even status /= 2 else: # odd status = status * 3 + 1 return euler_problem_14(value, status, n+1)def euler_problem_14_3(): terms = 0 value = 0 for x in xrange(100000): result = euler_problem_14_2() if result > terms: value = x terms = result print("value : %s terms: %s" % (value, terms))def ext15(n): if n > 1: yield n if n % 2 == 0: n /= 2 for i in ext15(n): yield i else: n = 3 * n + 1 for i in ext15(n): yield i else: yield ndef count12(): count = 0 count1 = 0 for i in xrange(200000): for k, j in enumerate(ext15(i)): count1 = k if count1 > count: (count1, count) = (count, count1) print count


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python最全学习路线(python路线规划)
下一篇:SpringBoot使用异步线程池实现生产环境批量数据推送
相关文章

 发表评论

暂时没有评论,来抢沙发吧~