6
\$\begingroup\$

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
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Did you get permission from the owner of the "second" code to make it publicly available and to licence it under CC-BY-SA? \$\endgroup\$ Commented Dec 30, 2016 at 20:33
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Jan 7, 2017 at 19:39

1 Answer 1

5
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you, that makes sense, and having the alphabet constant is a great point. \$\endgroup\$ Commented Dec 31, 2016 at 19:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.