当前位置:   article > 正文

《python基础教程》答案(第七章)_头歌python第七章作业答案

头歌python第七章作业答案

《python基础教程》答案(第七章)

Fridge.py

# created by swy
"""
solutions to beginning python
"""


class Fridge:
    def __init__(self, items={
   }):
        """
        Optionally pass in an initial dictionary of items
        :param items:
        """
        if type(items) != type({
   }):
            raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
        self.items = items
        return

    def __add_multi(self, food_name, quantity):
        if food_name not in self.items:
            self.items[food_name] = 0

        self.items[food_name] = self.items[food_name] + quantity

    def add_one(self, food_name):
        if type(food_name) != type(""):
            raise TypeError("add_one requires a string, given a %s" % type(food_name))
        else:
            self.__add_multi(food_name, 1)

        return True

    def add_many(self, food_dict):
        if type(food_dict) != type({
   }):
            raise TypeError("add_many requires a dictionary, got a %s" % food_dict)
        for item in food_dict.keys():
            self.__add_multi(item, food_dict[item])
        return

    def has(self, food_name, quantity=1):
        return self.has_various({
   food_name: quantity})

    def has_various(self, foods):
        try:
            for food in foods.keys():
                if self.items[food] < foods[food]:
                    return False
            return True
        except KeyError:
            return False

    def __get_multi(self, food_name, quantity):
        try:
            if self.items[food_name] is None:
                return False
            if quantity > self.items[food_name]:
                return False
            self.items[food_name] = self.items[food_name] - quantity
        except KeyError:
            return False
        return quantity

    def get_one(self, food_name):
        if type(food_name) != type(""):
            raise TypeError("get_one requires a string, given a %s" % type(food_name))
        else:
            result = self.__get_multi(food_name, 1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/785676
推荐阅读
相关标签
  

闽ICP备14008679号