[英]Optimizing function for execution speed
I am new to Python and I'm trying to optimize this code for large numbers.我是 Python 的新手,我正在尝试针对大量数据优化此代码。 However I'm struggling to find an optimized way.
但是我正在努力寻找优化的方法。 If I run it as it is, it takes almost 4 minutes.
如果我按原样运行它,大约需要 4 分钟。 I know it has something to do with loop and the max and randint function.
我知道它与循环和最大和随机数 function 有关。 I tried to use random.random as I read that is quicker but I got almost the same result.
我尝试使用 random.random ,因为我读得更快,但我得到了几乎相同的结果。 Can you think of a better way so it doesn't take that long?
你能想出一个更好的方法,这样就不需要那么长时间了吗?
from random import randint
def func(iters, n):
# Function to add max random numbers to a list.
l = [0]
for i in range(iters):
r = randint(0, n)
max_l = max(l)
if r > max_l:
l.append(r)
else:
l.append(max_l + 1)
return l
func(100000, 50)
Yes as mentioned by @quamrana the last index of the list contains the max so just access instead of calculating it every time.是的,正如@quamrana 提到的,列表的最后一个索引包含最大值,所以只需访问而不是每次都计算它。
from random import randint
def func(iters, n):
#Function to add max random numbers to a list.
l = [0]
for i in range(iters):
r = randint(0, n)
max_l = l[-1]
if r > max_l:
l.append(r)
else:
l.append(max_l + 1)
return l
func(100000, 50)
You can try using random.choice
function which is a bit faster :您可以尝试使用
random.choice
function 更快一点:
from random import choice
def func(iters, n):
# Function to add max random numbers to a list.
l = [0]
max_l = 0
random_numbers = list(range(n))
for _ in range(iters):
r = choice(random_numbers)
if r > max_l:
l.append(r)
max_l = r
else:
l.append(max_l + 1)
max_l += 1
return l
print(func(100000, 50))
And also you don't need to calculate max
every time.而且你不需要每次都计算
max
。 The last value you insert is always the max_l
value.您插入的最后一个值始终是
max_l
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.