|
| 1 | +class things: |
| 2 | + def __init__(self, n, v, w): |
| 3 | + self.name = n |
| 4 | + self.value = v |
| 5 | + self.weight = w |
| 6 | + |
| 7 | + def __repr__(self): |
| 8 | + return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" |
| 9 | + |
| 10 | + def get_value(self): |
| 11 | + return self.value |
| 12 | + |
| 13 | + def get_name(self): |
| 14 | + return self.name |
| 15 | + |
| 16 | + def get_weight(self): |
| 17 | + return self.weight |
| 18 | + |
| 19 | + def value_Weight(self): |
| 20 | + return self.value / self.weight |
| 21 | + |
| 22 | + |
| 23 | +def build_menu(name, value, weight): |
| 24 | + menu = [] |
| 25 | + for i in range(len(value)): |
| 26 | + menu.append(things(name[i], value[i], weight[i])) |
| 27 | + return menu |
| 28 | + |
| 29 | + |
| 30 | +def greedy(item, maxCost, keyFunc): |
| 31 | + itemsCopy = sorted(item, key=keyFunc, reverse=True) |
| 32 | + result = [] |
| 33 | + totalValue, total_cost = 0.0, 0.0 |
| 34 | + for i in range(len(itemsCopy)): |
| 35 | + if (total_cost + itemsCopy[i].get_weight()) <= maxCost: |
| 36 | + result.append(itemsCopy[i]) |
| 37 | + total_cost += itemsCopy[i].get_weight() |
| 38 | + totalValue += itemsCopy[i].get_value() |
| 39 | + return (result, totalValue) |
| 40 | + |
| 41 | + |
| 42 | +def test_greedy(): |
| 43 | + """ |
| 44 | + >>> food = ["Burger", "Pizza", "Coca Cola", "Rice", |
| 45 | + ... "Sambhar", "Chicken", "Fries", "Milk"] |
| 46 | + >>> value = [80, 100, 60, 70, 50, 110, 90, 60] |
| 47 | + >>> weight = [40, 60, 40, 70, 100, 85, 55, 70] |
| 48 | + >>> foods = build_menu(food, value, weight) |
| 49 | + >>> foods # doctest: +NORMALIZE_WHITESPACE |
| 50 | + [things(Burger, 80, 40), things(Pizza, 100, 60), things(Coca Cola, 60, 40), |
| 51 | + things(Rice, 70, 70), things(Sambhar, 50, 100), things(Chicken, 110, 85), |
| 52 | + things(Fries, 90, 55), things(Milk, 60, 70)] |
| 53 | + >>> greedy(foods, 500, things.get_value) # doctest: +NORMALIZE_WHITESPACE |
| 54 | + ([things(Chicken, 110, 85), things(Pizza, 100, 60), things(Fries, 90, 55), |
| 55 | + things(Burger, 80, 40), things(Rice, 70, 70), things(Coca Cola, 60, 40), |
| 56 | + things(Milk, 60, 70)], 570.0) |
| 57 | + """ |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + import doctest |
| 62 | + |
| 63 | + doctest.testmod() |
0 commit comments