2

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)
a'r
37.2k7 gold badges68 silver badges67 bronze badges
asked May 16, 2020 at 10:32
1
  • 1
    Your problem stems from max_l = max(l) which you calculate each time round. Instead you have the information for max_l at the end of each loop. Commented May 16, 2020 at 10:34

2 Answers 2

1

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)
answered May 16, 2020 at 10:43
Sign up to request clarification or add additional context in comments.

1 Comment

On my system, this changed the runtime from ~50 seconds to <1 second.
0

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.

answered May 16, 2020 at 10:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.