Collatz 序列
编写一个名为 collatz()的函数,它有一个名为 number 的参数。如果参数是偶数,那么 collatz()就打印出 number // 2, 并返回该值。如果 number 是奇数, collatz()就打印并返回 3 * number + 1。然后编写一个程序,让用户输入一个整数,并不断对这个数调用 collatz(), 直到函数返回值1(令人惊奇的是, 这个序列对于任何整数都有效, 利用这个序列,你迟早会得到 1! 既使数学家也不能确定为什么。 你的程序在研究所谓的“Collatz序列”,它有时候被称为“最简单的、 不可能的数学问题”)。
def collatz(number):
if number%2==0:
print(number//2)
return number//2
else:
print(3*number+1)
return 3*number+1
print('请输入一个整数:')
try:
n=int(input())
n=collatz(n)
while n!=1:
n=collatz(n)
except ValueError:
print('请输入整数')
运行结果
请输入一个整数:
3
10
5
16
8
4
2
1
>>>
注意事项:
记得将 input()的返回值用 int()函数转成一个整数,否则它会是一个字符串
逗号代码
假定有下面这样的列表:
spam = [‘apples’, ‘bananas’, ‘tofu’, ‘cats’]
编写一个函数,它以一个列表值作为参数,返回一个字符串。该字符串包含所有表项,表项之间以逗号和空格分隔,并在最后一个表项之前插入 and。例如,将前面的 spam 列表传递给函数,将返回’apples, bananas, tofu, and cats’。但你的函数应该能够处理传递给它的任何列表。
def toStr(alist):
astr=alist[0]
for i in range(1,len(alist)):
if i==len(alist)-1:
astr+='and '+alist[i]
else:
astr+=','+alist[i]
return astr
aList=[]
while 1:
tempstr=input()
if tempstr=='':
break
aList.append(tempstr)
print(toStr(aList))
运行结果
apple
pencil
orange
blue
white
apple,pencil,orange,blue and white
>>>
列表到字典的函数,针对好玩游戏物品清单
假设征服一条龙的战利品表示为这样的字符串列表:
dragonLoot = [‘gold coin’, ‘dagger’, ‘gold coin’, ‘gold coin’, ‘ruby’]
写一个名为 addToInventory(inventory, addedItems)的函数, 其中 inventory 参数是一个字典, 表示玩家的物品清单(像前面项目一样), addedItems 参数是一个列表,就像 dragonLoot。addToInventory()函数应该返回一个字典,表示更新过的物品清单。请注意,列表可以包含多个同样的项。你的代码看起来可能像这样:
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)
前面的程序将输出如下:
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
def addToInventory(inventory, addedItems):
for k in addedItems:
inventory[k]=inventory.setdefault(k,0)+1
return 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))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
运行结果
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48
>>>
表格打印
编写一个名为 printTable()的函数, 它接受字符串的列表的列表,将它显示在组织良好的表格中, 每列右对齐。假定所有内层列表都包含同样数目的字符串。例如,该值可能看起来像这样:
tableData = [[‘apples’, ‘oranges’, ‘cherries’, ‘banana’],
[‘Alice’, ‘Bob’, ‘Carol’, ‘David’],
[‘dogs’, ‘cats’, ‘moose’, ‘goose’]]
你的 printTable()函数将打印出:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
colWidths=[0]*len(tableData)
for i in range(len(tableData)):
for j in range(len(tableData[0])):
if colWidths[i]<len(tableData[i][j]):
colWidths[i]=len(tableData[i][j])
print(colWidths)
for n in range(len(tableData[0])):
for m in range(len(tableData)):
if m==0:
print(tableData[m][n].rjust(colWidths[m]),end=' ')
else:
print(tableData[m][n].ljust(colWidths[m]),end=' ')
print('\n')
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose