简体   繁体   English

为随机生成器优化python代码

[英]optimise python code for random generator

Could you please help me to optimize my first python program, I am trying to define a random generator, but somehow when I put a big number it hangs... 您能帮我优化我的第一个python程序吗,我正在尝试定义一个随机数生成器,但是以某种方式,当我放一个大数字时,它会挂起...

def rand(seed, x):
    if x == 1:
        return seed
    elif x == 2:
        return 1237
    elif x == 3:
        return 345892
    else:
        return ((31 * rand(seed, (x - 3))) + (103 * rand(seed, (x - 2))) + (7 * rand(seed, (x - 1))) + 500003) % 1000001

please try with: 请尝试:

print(rand(5, 5)), the result is : 506860

but when you use a bigger number its a problem, example: 但是当您使用更大的数字时,这是一个问题,例如:

print(rand(50, 50))

You can use dynamic programming : 您可以使用动态编程

def rand(seed, x):
  table = [seed, 1237, 345892]
  for _ in range(x - 3):
    next_num = table[-3] * 31 + table[-2] * 103 + table[-1] * 7 
    next_num += 500003
    next_num %= 1000001
    table.append(next_num)
  return table[-1]

The reason this is faster is that it only calculates each value once, while your code calculates things exponentially. 之所以更快,是因为它只计算每个值一次,而您的代码则以指数形式计算事物。

This algorithm is O(n) (for loop of length x - 3 ), while your algorithm was O(1.83...^n) ( 1.83^3=1+1.83+1.83^2 ). 该算法为O(n) (对于长度为x - 3循环),而您的算法为O(1.83...^n)1.83^3=1+1.83+1.83^2 )。

Alternately, as suggested in the comments, you can use functools.lru_cache : 或者,如注释中所建议,您可以使用functools.lru_cache

import functools

@functools.lru_cache()
def rand(seed, x):
  # insert your code here

This works in almost the same way as the previous code, but uses a decorator to memoize results instead of storing them in a list. 它的工作方式与以前的代码几乎相同,但是使用修饰符来记忆结果,而不是将其存储在列表中。

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

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