0

I am trying to retrieve a random string from python list to build a word guess challenge. I deployed anaconda environment on Alibaba Cloud ECS Instance.

I often use the following method to retrieve a random string from the list.

Let's say

WordStack=['A','B','C','D']
print(WordStack[random.randint(len(WordStack))])

Is there any optimized way or build-in funtion to do that? Due to a large number of words, it takes some time to give the result.

  • Both those operations have O(1) complexity (list's get item and randint). I doubt using a long list would make much of a difference. – ayhan Nov 26 '18 at 15:41
  • Exactly. The slowness must come from other parts of your code. – blhsing Nov 26 '18 at 15:41
  • @ayhan and `len` is also O(1) – Ma0 Nov 26 '18 at 15:42
  • @Ev.Kounis Yes, that too. It seems random.choice is implemented pretty much the same way: https://github.com/python/cpython/blob/master/Lib/random.py#L278 – ayhan Nov 26 '18 at 15:46
  • if loading is the slow part; think about using a different file format or tricks like: https://stackoverflow.com/a/28254628/1358308 – Sam Mason Nov 26 '18 at 16:09

2 Answers2

2

Take a look at random.choice which does exactly what you need. For your case, it would look like this:

WordStack = ['A','B','C','D']
random_str = random.choice(WordStack)
print(random_str)  # -> whatever

Having said that, I wouldn't expect it to make such a big difference on the speed of the process. But If I find the time I will test it.

Ma0
  • 15,057
  • 4
  • 35
  • 65
0

You could try random.randrange() instead of random.randint().

random.randrange():

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

From https://docs.python.org/3/library/random.html#random.randrange

I am not aware of any built-in function that does this.

So the equivalent statement would be:

WordStack[random.randrange(len(WordStack))]

Steven
  • 442
  • 3
  • 9