Interview Query

Weighted Keys

Start Timer

0:00:00

Upvote
12
Downvote
Save question
Mark as completed
View comments (41)
Next question

Given a dictionary with weights, write a function random_key that returns a key at random with a probability proportional to the weights.

Example 1:

Input:

weights = {'A': 1, 'B': 2}

Output:

random_key(weights) -> return A 1/3 of the time, B 2/3 of the time

Example 2:

Input:

weights = {'A': 1, 'B': 1}

Output:

random_key(weights) -> return A 1/2  of the time, B 1/2  of the time
.
.
.
.
.


Comments

Loading comments...