2015年10月16日金曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Automate the Boring Stuff with Python: Practical Programming for Total Beginners (Al Sweigart (著)、No Starch Press)のPart Ⅰ.(Python Programming Basics)、Chapter 5.(Dictionaries and Structuring Data)、Practice Projects: Practice Projects(List to Dictionary Function for Fantasy Game Inventory)を解いてみる。

Practice Projects: Practice Projects(List to Dictionary Function for Fantasy Game Inventory)

コード(Emacs)

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

def display_inventory(inventory):
    print("Inventory:")
    total = 0
    for k, v in inventory.items():
        print('{0} {1}'.format(v, k))
        total += v
    print('\nTotal number of items: {0}'.format(total))

def add_to_inventory(inventory, added_items):
    for item in added_items:
        inventory[item] = inventory.get(item, 0) + 1
    return inventory

inv = {'gold coin': 42, 'rope':1}    
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

inv = add_to_inventory(inv, dragon_loot)
display_inventory(inv)

入出力結果(Terminal, IPython)

$ ./sample1.py
Inventory:
1 rope
1 ruby
1 dagger
45 gold coin

Total number of items: 48
$

0 コメント:

コメントを投稿