2

I am writing a Python code to generate random sentences using context free grammar.

Each non-terminal/terminal symbol has a weight associated with it.

Currently I am using random.choice() to select an element from the defaultdict(list). This gives me an output giving all the elements of the list an equal probability.

How can I select an element if probability of each element is different?

I have a context free grammar in the form of:
Weight NT NT/T

Example:
70 NounPhrase A
30 NounPhrase B

So probability of 1st NP to get selected would be 70/(70+30) and second would be 30/(70+30). So how can I use this concept with random in Python?

Kreena Mehta
  • 303
  • 1
  • 5
  • 16

0 Answers0