recipe-577460.py 文件源码

python
阅读 17 收藏 0 点赞 0 评论 0

项目:code 作者: ActiveState 项目源码 文件源码
def __init__(self, items = None):
        """Create a dictionary from iters.

        If items can't be fed to a dictionary, it will be interpreted as a 
        collection of keys, and each value will default to value 1/n. Otherwise,
        the values are normalized to sum to one. Raises ValueError if
        some values are not numbers or are negative.

        Arguments:
        - `items`: argument with which to make dictionary

        """
        if items is None: return dict.__init__(self)
        try:
            # can fail if items is not iterable or not full of size 2 items:
            dict.__init__(self, items)
        except TypeError:
            try:
                # Let's assume items is a finite iterable full of keys
                vals = [1/len(items)] * len(items)
            except TypeError:
                # Apparently items has no length -- let's take it as the only
                # key and put all the probability on it.
                dict.__init__(self, (items, 1))
            else:
                # if items has a length, it can be iterated through with zip
                dict.__init__(self, zip(items, vals))
        else:
            # we've successfully made dic from key, value pairs in items, now let's 
            # normalize the dictionary, and check the values
            for v in self.values():
                if not isinstance(v, Real):
                    raise TypeError("Values must be nonnegative real numbers so I " +
                               "can properly normalize them. " + str(v) + " is not.")
                elif v < 0:
                    raise ValueError("Values must be nonnegative, unlike " + str(v))

            tot = sum(self.values())
            for k, v in self.items(): self[k] = v/tot
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号