Optimizing function for execution speed

Viewed 61

I am new to Python and I'm trying to optimize this code for large numbers. However I'm struggling to find an optimized way. If I run it as it is, it takes almost 4 minutes. I know it has something to do with loop and the max and randint function. I tried to use random.random as I read that is quicker but I got almost the same result. 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)
2 Answers

Yes as mentioned by @quamrana the last index of the list contains the max so just access instead of calculating it every time.

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:

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. The last value you insert is always the max_l value.

Related