diff --git a/exercises/ex05/ex05b.py b/exercises/ex05/ex05b.py index e69de29..1506ad5 100644 --- a/exercises/ex05/ex05b.py +++ b/exercises/ex05/ex05b.py @@ -0,0 +1,29 @@ +import sys + +tests = [ + {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}, + {'rope': 1, 'torch': 6, 'gold coin': "a", 'dagger': 1, 'arrow': 12}, + None, +] + + +def displayInventory(inventory): + msg = "Inventory:\n" + total = 0 + if not isinstance(inventory, dict): + return False, "Invalid inventory type" + for item, amount in inventory.items(): + msg += f"{amount} {item}\n" + if not isinstance(amount, int): + return False, f"Invalid amount for '{item}'" + total += amount + return True, f"{msg}Total number of items: {total}" + + +valid = True +for inventory in tests: + print(f"Testing inventory '{inventory}': ") + valid, msg = displayInventory(inventory) + print(msg) +if not valid: + sys.exit(1) diff --git a/exercises/ex05/ex05c.py b/exercises/ex05/ex05c.py index e69de29..6e1d322 100644 --- a/exercises/ex05/ex05c.py +++ b/exercises/ex05/ex05c.py @@ -0,0 +1,40 @@ +import sys + +dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] +tests = [ + {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}, + {'rope': 1, 'torch': 6, 'gold coin': "a", 'dagger': 1, 'arrow': 12}, + None, +] + + +def displayInventory(inventory): + msg = "Inventory:\n" + total = 0 + if not isinstance(inventory, dict): + return False, "Invalid inventory type" + for item, amount in inventory.items(): + msg += f"{amount} {item}\n" + if not isinstance(amount, int): + return False, f"Invalid amount for '{item}'" + total += amount + return True, f"{msg}Total number of items: {total}" + + +def addToInventory(inv, items): + for item in items: + inv.setdefault(item, 0) + inv[item] += 1 + return inv + + +valid = True +for inventory in tests: + print(f"Testing inventory addition with '{dragonLoot}': ") + valid, msg = displayInventory(inventory) + if valid: + inventory = addToInventory(inventory, dragonLoot) + valid, msg = displayInventory(inventory) + print(msg) +if not valid: + sys.exit(1)