If given two lists a: ['the', 'a', 'and', 'for'] and b: [0.2, 0.3, 0.4, 0.1], the positions of the numbers in b represents the weights for the respective probabilities of obtaining the corresponding word. E.g. the : 20%, a : 30%, etc. Create a function that will generate words based on their corresponding probabilities.
import random def weighted_word_selection(words, weights): """ words : an array of strings (words) weights : an array of floats (corresponding probabilties based on) index number. """ start = 0 for i in range(len(weights)): weights[i] = start+weights[i] start += weights[i] r = random.uniform(0, 1.0) for i in range(len(weights)): if r < weights[i]: return words[i]
- What are some alternative ways to solve this, bearing in mind the requirement to optimize performance as the array words and the array weights approaches a large n? Any detailed explanations of underlying processes such as Cython/C based Python solutions are helpful.
- Can you discuss the \$O(n)\$ based complexity of the problem and some performance issues in my solution, and how those are addressed in your suggested solution at scale?