HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Random string generating function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomfunctiongeneratingstring

Problem

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

Solution

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.

Code Snippets

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))

Context

StackExchange Code Review Q#151284, answer score: 5

Revisions (0)

No revisions yet.