我的python程序中的算法错误

时间:2016-06-22 02:08:46

标签: python

当我运行它时,金币的数量只增加一,尽管有三个额外的金币。我不知道我的逻辑有什么问题。我创造了两个功能; addToInventory,它将字典作为第一个参数,将列表作为第二个参数。如果字典中不存在该键,则该函数会将该键添加到字典中,并将该值递增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个:stuff中的原始40加上dragonLoot中的另外两个。

3 个答案:

答案 0 :(得分:1)

定义dragonLoot时,您要定义set。集合是无序的,只有一个给定的术语。在python中,花括号用于定义字典或集合 - 如果它是键:值对,它是一个字典,否则它是一个集合。为了保持顺序和编号,我们要么是元组(通常使用(foo,bar,coin,)形式定义),要么是列表(使用[foo,bar,coin]定义)。

答案 1 :(得分:0)

首先需要将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)

答案 2 :(得分:0)

你的功能中的逻辑是足够的,但你选择{set}为" dragon_loot"数据类型不合逻辑;)

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