During an interview, I was given the following coding question that I couldn't figure out. I've been thinking about it ever since then, and I can't seem to figure out how to write a function that returns a value for a given percent of the time.
The question goes as follows:
Say you have a dictionary dict = {'A': 10, 'B': 30, 'C': 60}. Write a function that returns 'A' 10% of the time, 'B' 30% of the time, and 'C' 60% of the time. So, the function should take in a dictionary with values as numbers (they don't necessarily have to add up to 100), and it should return that value's key in correspondence with the percentage that key is to the sum of all the keys.
I have an idea of how to start the function...
def percent_return(dict):
sum = 0
for key, value in dict.items():
sum += float(value)
percent_array = []
for key, value in dict.items():
percent = float(value) / sum
percent_array.append(percent)
''' We now have an array with the associated percentages for the dictionary,
but now I don't know how to actually apply this to the return values '''
for key, value in dict.items():
if (something that indicates given %):
return key
I'm very new to python, so please excuse my ignorance and thanks for your help!
There are several issues with your code:
sum and dict built-ins. Never do this.The built-in random.choice already has this functionality. For efficiency, you can use sum with dict.values directly and use a dictionary comprehension to calculate weights. Since random.choices returns a list, we can use next with iter to extract the only element.
from random import choices
d_weights = {'A': 10, 'B': 30, 'C': 60}
def percent_return(d):
val_sum = sum(d.values())
d_pct = {k: v/val_sum for k, v in d.items()}
return next(iter(choices(population=list(d_pct), weights=d_pct.values(), k=1)))
res = percent_return(d_weights)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With