在一次面试中,我被问到了以下我无法理解的编码问题。从那以后我就一直在考虑这个问题,我似乎不知道如何编写一个函数,在给定的时间内返回一个值。在
问题如下:
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.
我知道如何启动函数。。。在
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
我对python很陌生,请原谅我的无知,谢谢你的帮助!在
会是这样吗。。。我不确定我是否理解这个问题,尽管我的代码会根据它们的“机会”打印出每个键。
您的代码有几个问题:
sum
和dict
内建。千万不要这样做。在内置的}来提取唯一的元素。
random.choice
已经具有此功能。为了提高效率,可以直接使用sum
和dict.values
并使用字典理解来计算权重。由于random.choices
返回一个列表,我们可以使用next
和{您可以使用
random.randrange
来绘制一个介于0和所有dict值之和之间的值,使用itertools.accumulate
从这些值生成一系列累积和,然后使用itertools.dropwhile
查找不小于draw的第一个累积和,并在该索引处返回dict的键,伴随着使用enumerate
的累计和:因此:
^{pr2}$can输出:
相关问题 更多 >
编程相关推荐