设为首页收藏本站

塞爱维(CIV)文明联盟

 找回密码
 注册
查看: 3289|回复: 7

[已解决] Python练习项目

[复制链接]
发表于 2017-1-19 22:13:18 | 显示全部楼层 |阅读模式
《Python自动化无聊事务》第3章练习项目:考拉兹数列

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.
  1. # collatz.py: Collatz sequence

  2. import sys

  3. def collatz(number):
  4.     if number % 2 == 0:
  5.         print(number // 2)
  6.         return number // 2
  7.     else:
  8.         print(3 * number + 1)
  9.         return 3 * number + 1

  10. print('Enter number:')
  11. try:
  12.     inNumber = int(input())
  13. except ValueError:
  14.     print('You must enter an integer.')
  15.     sys.exit()

  16. while inNumber > 1:
  17.     inNumber = collatz(inNumber)
复制代码
 楼主| 发表于 2017-1-21 23:28:42 | 显示全部楼层
第4章练习项目:显示列表内容
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.
  1. # showList.py: Comma Code

  2. def showList(inList):
  3.     outStr = ''
  4.     for i in range(len(inList)):
  5.         if i == 0:
  6.             outStr += inList[0]
  7.         elif i == len(inList) - 1:
  8.             outStr += ' and ' + inList[-1]
  9.         else:
  10.             outStr += ', ' + inList[i]
  11.     return outStr

  12. spam = ['apples', 'bananas', 'tofu', 'cats']
  13. print(showList(spam))
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-1-22 14:11:30 | 显示全部楼层
第4章练习项目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.
  1. # charPic.py: Character Picture Grid

  2. grid = [['.', '.', '.', '.', '.', '.'],
  3.         ['.', 'O', 'O', '.', '.', '.'],
  4.         ['O', 'O', 'O', 'O', '.', '.'],
  5.         ['O', 'O', 'O', 'O', 'O', '.'],
  6.         ['.', 'O', 'O', 'O', 'O', 'O'],
  7.         ['O', 'O', 'O', 'O', 'O', '.'],
  8.         ['O', 'O', 'O', 'O', '.', '.'],
  9.         ['.', 'O', 'O', '.', '.', '.'],
  10.         ['.', '.', '.', '.', '.', '.']]

  11. for y in range(len(grid[0])):
  12.     for x in range(len(grid)):
  13.         print(grid[x][y], end='')
  14.     print('\n')
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-1-23 18:01:20 | 显示全部楼层
第5章练习项目:游戏物品栏
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
  1. # inventory.py: Fantasy Game Inventory

  2. def displayInventory(inventory):
  3.     print("Inventory:")
  4.     item_total = 0
  5.     for k, v in inventory.items():
  6.         print(str(v) + ' ' + k)
  7.         item_total += v
  8.     print("\nTotal number of items: " + str(item_total))

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

  15. inv = {'gold coin': 42, 'rope': 1}
  16. dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
  17. inv = addToInventory(inv, dragonLoot)
  18. displayInventory(inv)
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-1-25 10:19:27 | 显示全部楼层
第6章练习项目:表格输出
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.
  1. # tablePrinter.py: Table Printer
  2. def printTable(inList):
  3.     colWidths = [0] * len(inList)
  4.     for x in range(len(inList)):
  5.         for i in inList[x]:
  6.             if colWidths[x] < len(i):
  7.                 colWidths[x] = len(i)
  8.     for y in range(len(inList[0])):
  9.         for x in range(len(inList)):
  10.             print(inList[x][y].rjust(colWidths[x]), end=' ')
  11.         print('\n')

  12. tableData = [['apples', 'oranges', 'cherries', 'banana'],
  13.              ['Alice', 'Bob', 'Carol', 'David'],
  14.              ['dogs', 'cats', 'moose', 'goose']]
  15. printTable(tableData)
复制代码
回复 支持 反对

使用道具 举报

发表于 2017-1-25 21:09:07 | 显示全部楼层
自己思考反复试错最后参考你的答案,再仔细思考后重新写一遍的答案。
  1. import sys

  2. def collatz(number):
  3.     if number % 2 == 0:
  4.         number = number // 2
  5.     else:
  6.         number = number * 3 +1
  7.     print(number)  
  8.     return number

  9. print('Enter an Integer')
  10. try:
  11.     number=int(input())
  12. except ValueError:
  13.     print('Error: must enter an integer.')
  14.     sys.exit()

  15. while number > 1:
  16.     number = collatz(number)
  17. while number < 1:
  18.     print('0 and negative integer is forbidden')
  19.     break
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-1-30 15:00:33 来自手机 | 显示全部楼层
看完前六章,可以开发些应用的脚本~
回复 支持 反对

使用道具 举报

发表于 2017-12-28 15:19:53 | 显示全部楼层
本帖最后由 西艾薇.F.Mars 于 2017-12-28 15:22 编辑

我想释放沉默术
沉默术没天赋强化,只有3d
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|塞爱维(CIV)文明联盟    

GMT+8, 2024-3-29 02:20

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表