Ejercicios 5b-c

This commit is contained in:
perro tuerto 2023-03-02 16:55:19 -08:00
parent 96bde3c362
commit f0183fa536
2 changed files with 69 additions and 0 deletions

View File

@ -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)

View File

@ -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)