《Python自動化無聊事務(wù)》練習(xí)項目

看到一篇文章推薦讲逛,我找了本 Automate the Boring Stuff with Python
每天學(xué)一點,今后碰到什么重復(fù)性的工作時希望能用得上……

第3章(函數(shù))練習(xí)項目:考拉茲數(shù)列

The Collatz Sequence
Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1.

The output of this program could look something like this:
Enter number:
3
10
5
16
8
4
2
1

Input Validation
Add try and except statements to the previous project to detect whether the user types in a noninteger string. Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy'). In the except clause, print a message to the user saying they must enter an integer.

# collatz.py: Collatz sequence

import sys

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    else:
        print(3 * number + 1)
        return 3 * number + 1

print('Enter number:')
try:
    inNumber = int(input())
except ValueError:
    print('You must enter an integer.')
    sys.exit()

while inNumber > 1:
    inNumber = collatz(inNumber)

第4章(列表)練習(xí)項目:顯示列表內(nèi)容

Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.

# showList.py: Comma Code

def showList(inList):
    outStr = ''
    for i in range(len(inList)):
        if i == 0:
            outStr += inList[0]
        elif i == len(inList) - 1:
            outStr += ' and ' + inList[-1]
        else:
            outStr += ', ' + inList[i]
    return outStr

spam = ['apples', 'bananas', 'tofu', 'cats']
print(showList(spam))

第4章(列表)練習(xí)項目2:字符圖案

Character Picture Grid
Say you have a list of lists where each value in the inner lists is a one-character string, like this:
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The (0, 0) origin will be in the upper-left corner, the x-coordinates increase going right, and w the y-coordinates increase going down.
Copy the previous grid value, and write code that uses it to print the image.
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
Hint: You will need to use a loop in a loop in order to print grid[0][0], then grid[1][0], then grid[2][0], and so on, up to grid[8][0]. This will finish the first row, so then print a newline. Then your program should print grid[0][1], then grid[1][1], then grid[2][1], and so on. The last thing your program will print is grid[8][5].
Also, remember to pass the end keyword argument to print() if you don’t want a newline printed automatically after each print() call.

# charPic.py: Character Picture Grid

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

for y in range(len(grid[0])):
    for x in range(len(grid)):
        print(grid[x][y], end='')
    print('\n')

第5章(字典)練習(xí)項目:游戲物品欄
Fantasy Game Inventory
You are creating a fantasy video game. The data structure to model the player’s inventory will be a dictionary where the keys are string values describing the item in the inventory and the value is an integer value detailing how many of that item the player has. For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so on.
Write a function named displayInventory() that would take any possible “inventory” and display it like the following:

Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 63

Hint: You can use a for loop to loop through all the keys in a dictionary.

List to Dictionary Function for Fantasy Game Inventory
Imagine that a vanquished dragon’s loot is represented as a list of strings like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item. Your code could look something like this:

def addToInventory(inventory, addedItems):
    # your code goes here

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

The previous program (with your displayInventory() function from the previous project) would output the following:

Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48

# inventory.py: Fantasy Game Inventory

def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))

def addToInventory(inventory, addedItems):
    # my code goes here
    for i in addedItems:
        inventory.setdefault(i, 0)
        inventory[i] += 1
    return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

第6章(操作字符串)練習(xí)項目:表格輸出

Table Printer
Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
Your printTable() function would print the following:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
Hint: Your code will first have to find the longest string in each of the inner lists so that the whole column can be wide enough to fit all the strings. You can store the maximum width of each column as a list of integers. The printTable() function can begin with colWidths = [0] * len(tableData), which will create a list containing the same number of 0 values as the number of inner lists in tableData. That way, colWidths[0] can store the width of the longest string in tableData[0], colWidths[1] can store the width of the longest string in tableData[1], and so on. You can then find the largest value in the colWidths list to find out what integer width to pass to the rjust() string method.

# tablePrinter.py: Table Printer

def printTable(inList):
    colWidths = [0] * len(inList)
    for x in range(len(inList)):
        for i in inList[x]:
            if colWidths[x] < len(i):
                colWidths[x] = len(i)
    for y in range(len(inList[0])):
        for x in range(len(inList)):
            print(inList[x][y].rjust(colWidths[x]), end=' ')
        print('\n')

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市播演,隨后出現(xiàn)的幾起案子蹬挤,更是在濱河造成了極大的恐慌,老刑警劉巖调鲸,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件盛杰,死亡現(xiàn)場離奇詭異,居然都是意外死亡藐石,警方通過查閱死者的電腦和手機即供,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來于微,“玉大人逗嫡,你說我怎么就攤上這事饶号〈媪В” “怎么了?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵恋脚,是天一觀的道長恋腕。 經(jīng)常有香客問我抹锄,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任伙单,我火速辦了婚禮获高,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘吻育。我一直安慰自己念秧,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布扫沼。 她就那樣靜靜地躺著出爹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪缎除。 梳的紋絲不亂的頭發(fā)上严就,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天,我揣著相機與錄音器罐,去河邊找鬼梢为。 笑死,一個胖子當(dāng)著我的面吹牛轰坊,可吹牛的內(nèi)容都是我干的铸董。 我是一名探鬼主播,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼肴沫,長吁一口氣:“原來是場噩夢啊……” “哼粟害!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起颤芬,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤悲幅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后站蝠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體汰具,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年菱魔,在試婚紗的時候發(fā)現(xiàn)自己被綠了留荔。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡澜倦,死狀恐怖聚蝶,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情藻治,我是刑警寧澤碘勉,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站栋艳,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏句各。R本人自食惡果不足惜吸占,卻給世界環(huán)境...
    茶點故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一晴叨、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧矾屯,春花似錦兼蕊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至排作,卻和暖如春牵啦,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背妄痪。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工哈雏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人衫生。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓裳瘪,卻偏偏與公主長得像,于是被迫代替她去往敵國和親罪针。 傳聞我的和親對象是個殘疾皇子彭羹,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內(nèi)容