函数,返回tim的某个百分比的值

2024-04-24 22:25:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在一次面试中,我被问到了以下我无法理解的编码问题。从那以后我就一直在考虑这个问题,我似乎不知道如何编写一个函数,在给定的时间内返回一个值。在

问题如下:

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很陌生,请原谅我的无知,谢谢你的帮助!在


Tags: ofthetokeyinfordictionaryreturn
3条回答

会是这样吗。。。我不确定我是否理解这个问题,尽管我的代码会根据它们的“机会”打印出每个键。

from random import randint

example = {
    'A': 10,
    'B': 50,
    'C': 80
}

def percent_return(dictionary):
    for key, value in dictionary.items():
        if randint(1, 100) < value:
            yield key

for char in percent_return(example):
    print(char)

您的代码有几个问题:

  1. 您可以隐藏sumdict内建。千万不要这样做。在
  2. 您正确地计算了百分比数组,但尚未将它们链接到键。在
  3. 从键中检索加权样本是没有逻辑的。在

内置的random.choice已经具有此功能。为了提高效率,可以直接使用sumdict.values并使用字典理解来计算权重。由于random.choices返回一个列表,我们可以使用next和{}来提取唯一的元素。

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)

您可以使用random.randrange来绘制一个介于0和所有dict值之和之间的值,使用itertools.accumulate从这些值生成一系列累积和,然后使用itertools.dropwhile查找不小于draw的第一个累积和,并在该索引处返回dict的键,伴随着使用enumerate的累计和:

import random
from itertools import accumulate, dropwhile
def pick(d):
    draw = random.randrange(sum(d.values()))
    return list(d.keys())[next(dropwhile(lambda t: t[1] < draw, enumerate(accumulate(d.values()))))[0]]

因此:

^{pr2}$

can输出:

Counter({'C': 587, 'B': 286, 'A': 127})

相关问题 更多 >