Random string generating function

Both these functions take in a sentence and generate a random string based of the length of sentence.

Mine, the first one, runs 4 times more slowly than the second one (someone else's code), but I don't know why and I'd like to understand what's happening 'under the hood' that makes it this way. If anything I would've expected numpy to be faster, which makes me think it's something else entirely.

Also, is there a way to make the first function even faster?

import random
import numpy as np

def generate_guess(sentence):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ']
return [np.random.choice(alphabet) for i in range(len(sentence))]


Don't review this one:

def generate_guess(sentence):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
res = ''
for i in range(len(sentence)):
res = res + alphabet[random.randrange(len(alphabet))]
return res

• Did you get permission from the owner of the "second" code to make it publicly available and to licence it under CC-BY-SA? – 301_Moved_Permanently Dec 30 '16 at 20:33
• @MathiasEttinger, I did not, I have no idea what CC-BY-SA is but I'll look it up. It's from an online textbook that the author makes completely freely publicly available, so I thought it would be fine. But as I said I'll look into what you mentioned. – jeremy radcliff Jan 7 '17 at 19:39

np.random.choice takes an additional argument specifying how many elements should be chosen. You can also use the built-in module string to save having to spell out the alphabet:

import numpy as np
import string

ALPHABET = np.array(list(string.ascii_lowercase + ' '))

def generate_guess(sentence):
return np.random.choice(ALPHABET, size=len(sentence))


I also made the alphabet a constant to avoid having to build it again and again.

Your code was not faster because you did not take advantage of the vector-wise operations of numpy. Neither your starting array, the alphabet, nor your output array were actual numpy arrays.

• Thank you, that makes sense, and having the alphabet constant is a great point. – jeremy radcliff Dec 31 '16 at 19:02