python程序中的算法错误

2024-06-16 08:41:07 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行它时,金币的数量只增加了一个,尽管有三个额外的金币。我不知道我的逻辑有什么问题。我创建了两个函数:addToInventory,第一个参数是dictionary,第二个参数是list。如果字典中不存在键,则函数会将键添加到字典中,并将值递增1。displayInventory方法打印字典中的键/值。以下是我的源代码:

#fantasyGameInventory.py - a function that displays the inventory from a
#dictionary data structure

stuff = {'rope': 1, 'torch': 6, 'gold coin': 40, 'dagger': 1, 'arrow': 12}
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}

def addToInventory(inventory, addedItems):
    #Iterate through the list 
    for k in addedItems:
       #if key not in the dictionary, add to the dictionary and set its value to zero
        inventory.setdefault(k,0)
        inventory[k] = inventory[k] + 1
        print(str(inventory[k]))

def displayInventory(inventory):
    print('Inventory:')
    itemTotal = 0
    #iterate through the dictionary and print the key/values
    for k, v in inventory.items():
        print(k + ': ' + str(v))
        itemTotal = itemTotal + v
        print ('Total number of items: ' + str(itemTotal))

addToInventory(stuff, dragonLoot)
displayInventory(stuff) 

它说有41枚金币,尽管显然应该有42枚:原来的40枚来自stuff,加上另外两枚在dragonLoot。你知道吗


Tags: theindictionary字典inventorycoinprintstuff
3条回答

首先需要将set更改为tuple,因为它在遍历列表时跳过重复的条目。你知道吗

以下是工作代码:

stuff = {'rope': 1, 'torch': 6, 'gold coin': 40, 'dagger': 1, 'arrow': 12}
dragonLoot = ('gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby')

def addToInventory(inventory, addedItems):
    #Iterate through the list
    for k in addedItems:
        #if key not in the dictionary, add to the dictionary and set its value to zero
        inventory.setdefault(k,0)
        #increment value by one
        inventory[k] = inventory[k] + 1
        print(str(inventory[k]))

def displayInventory(inventory):
    print('Inventory:')
    itemTotal = 0
    #iterate through the dictionary and print the key/values
    for k, v in inventory.items():
        print(k + ': ' + str(v))
        itemTotal = itemTotal + v
    print ('Total number of items: ' + str(itemTotal))

addToInventory(stuff, dragonLoot)
displayInventory(stuff)

函数中的逻辑已经足够了,但是为“dragon\u loot”数据类型选择{set}是不合逻辑的;)

'''
started: yyyymmdd@time
fantasyGameInventory.py - a pair of functions which
add items in a list to an inventory dictionary and
display the inventory from a dictionary data structure
finished: yyyymmdd@time
author: your_name_here
'''

stuff = {'rope': 1, # a dict
         'torch': 6,
         'gold coin': 40,
         'dagger': 1,
         'arrow': 12}
dragon_loot = ['gold coin', # a list
               'dagger',
               'gold coin',
               'gold coin',
               'ruby']
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}

print ('"stuff" is a {}'.format(type(stuff)))
print ('"dragon_loot" is a {}, and'.format(type(dragon_loot)))
print ('"dragonLoot" was a {} (with a camelCase binding)'.format(type(dragonLoot)))
print ()
print ('Wha\' happen\' to all the gold???\n{}'.format(dragonLoot))
print ()


def add_to_inventory(inventory_dict, item_list):
    '''
    Iterate through a list of items to be added to an
    inventory dictionary. If key not already in the
    dictionary, it gets added to the dictionary
    and its value set to zero, then the value is updated
    '''
    for item in item_list:
        inventory_dict.setdefault(item, 0)
        inventory_dict[item] += 1
        print('{} {}'.format(str(inventory_dict[item]), str(item)))


def display_inventory(inventory_dict):
    '''
    Display the inventory from a dictionary data structure.
    '''
    print('Inventory contents (unordered):')
    total_num_items = 0
    # iterate through the dictionary and print the 'k'ey/'v'alue pairs
    for k, v in inventory_dict.items():
        print('{}: {}'.format(k, str(v)))
        total_num_items += v
    print ('Total number of items: {}'.format(str(total_num_items)))

add_to_inventory(stuff, dragon_loot)
display_inventory(stuff)

定义dragonLoot时,就是在定义一个set。集合是无序的,并且只有一个给定的项。在python中,大括号用于定义字典或集合—如果是键:值对,则是dict,否则是set。为了保持顺序和编号,我们可以使用元组(通常使用(foo,bar,coin,)形式定义)或列表(使用[foo,bar,coin]定义)。你知道吗

相关问题 更多 >