Anonymous
Автоматизируйте скучные вещи с помощью Python — Глава 5, Список фэнтезийных игр
Сообщение
Anonymous » 16 дек 2024, 21:59
Ниже приведен код, который я тестировал:
Код: Выделить всё
stuff = {'arrow':12, 'gold coin':42, 'rope':1, 'torch':6, 'dagger':1}
def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + str(k))
item_total += v
print('Total number of items: ' + str(item_total))
displayInventory(stuff)
##
inv = {'gold coin':42, 'rope':1}
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
def addToInventory(inventory, addedItems):
for i in addedItems:
inventory.setdefault(i, 0)
inventory[i] += 1
return inventory
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
Я ожидал, что он вернется
Код: Выделить всё
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 46
Но я получаю только 43 за ключ «золотая монета». Почему это?
Подробнее здесь:
https://stackoverflow.com/questions/589 ... -inventory
1734375575
Anonymous
Ниже приведен код, который я тестировал: [code]stuff = {'arrow':12, 'gold coin':42, 'rope':1, 'torch':6, 'dagger':1} def displayInventory(inventory): print('Inventory:') item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + str(k)) item_total += v print('Total number of items: ' + str(item_total)) displayInventory(stuff) ## inv = {'gold coin':42, 'rope':1} dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'} def addToInventory(inventory, addedItems): for i in addedItems: inventory.setdefault(i, 0) inventory[i] += 1 return inventory dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'} inv = addToInventory(inv, dragonLoot) displayInventory(inv) [/code] Я ожидал, что он вернется [code]Inventory: 45 gold coin 1 rope 1 dagger 1 ruby Total number of items: 46 [/code] Но я получаю только 43 за ключ «золотая монета». Почему это? Подробнее здесь: [url]https://stackoverflow.com/questions/58928763/automate-the-boring-stuff-with-python-chapter-5-fantasy-game-inventory[/url]