6-16.
矩陣。處理矩陣M和N的加和乘操作。
【答案】
(a)M和N的加作業碼如下:
def matrix_input(string, m, n):
matrix = []
a = string.split(',')
for i in range(m * n):
matrix.append(a[i])
return matrix
def matrix_display(matrix, m, n):
for i in range(m):
for j in range(n):
print matrix[i * n + j],
print '\r'
M_row = int(raw_input('The number of rows: ... '))
C_column = int(raw_input('The number of cloumns: ... '))
matrix_M_string = raw_input('Please input the M matrix (in list, row by row): ... ')
matrix_M = matrix_input(matrix_M_string, M_row, C_column)
matrix_N_string = raw_input('Please input the N matrix (in list, row by row): ... ')
matrix_N = matrix_input(matrix_N_string, M_row, C_column)
# From cnblogs.com/balian/
matrix_C = []
for i in range(M_row * C_column):
matrix_C.append(int(matrix_M[i]) + int(matrix_N[i]))
print 'Matrix M:'
matrix_display(matrix_M, M_row, C_column)
print 'Matrix N:'
matrix_display(matrix_N, M_row, C_column)
print 'M + N:'
matrix_display(matrix_C, M_row, C_column)
【執行結果】
The number of rows: ... 2
The number of cloumns: ... 3
Please input the M matrix (in list, row by row): ... 1,2,3,4,5,6
Please input the N matrix (in list, row by row): ... 1,0,0,1,1,1
Matrix M:
1 2 3
4 5 6
Matrix N:
1 0 0
1 1 1
M + N:
2 2 3
5 6 7
【未完】一時找不到完成矩陣乘操作的聰明辦法。按照定義來計算有些麻煩。
6-17.
方法。實現一個叫myPop()的函數,功能類似於列表的pop()方法,用一個列表作為輸入,移除列表的最新一個元素,並返回它。
【答案】
代碼如下:
def myPop(list):
return list[0:len(list)-1]
list_string = raw_input('Please input the list: ... ')
list = []
a = list_string.split(',')
for i in a:
list.append(int(i))
print myPop(list)
【執行結果】
Please input the list: ... 1, 2, 3, 4, 5
[1, 2, 3, 4]
【評論】
我認為作者是希望讀者按照例子例子6.3或者6.4來處理這個題目。
6-18.
zip()內建函數。在6.13.2節裡面關於zip()函數的例子中,zip(fn,ln)返回的是什嗎?
【答案】
>>> fn = ['ian', 'stuart', 'david']
>>> ln = ['bairnson', 'elliott', 'paton']
>>> zip(fn, ln)
[('ian', 'bairnson'), ('stuart', 'elliott'), ('david', 'paton')]
>>> for i, j in zip(fn, ln):
... print ('%s %s' % (i, j)).title()
...
Ian Bairnson
Stuart Elliott
David Paton
6-19.
多列輸出。有任意項的序列或者其他容器,把它們等距離分列顯示。由調用者提供資料和輸出格式。例如,如果你傳入100個項並定義3列輸出,按照需要的模式顯示這些資料。這種情況下,應該是兩列顯示33個項,最後一列顯示34個。你可以讓使用者來選者水平排序或者垂直排序。
【答案】
代碼如下:
def list_display(list, N, F):
num = len(list)/N
if F == 0 and (len(list) - num * N) == 0:
for i in range(N):
for j in range(num):
print list[i * num + j],
print '\r'
if F == 0 and (len(list) - num * N) > 0:
for i in range(N-1):
for j in range(num):
print list[i * num + j],
print '\r'
for k in list[(N - 1) * num:]:
print k,
print '\r'
list_string = raw_input('Please input the list: ... ')
num = raw_input('How many rows/columns in display: ... ')
state = raw_input('(H)orizontal or (V)ertical: ... ').lower()
CMDs = {'h' : 0, 'v' : 1}
list = []
a = list_string.split(',')
for i in a:
list.append(int(i))
list_display(list, int(num), CMDs[state])
【執行結果】
Please input the list: ... 1,2,3,4,5,6,7
How many rows/columns in display: ... 2
(H)orizontal or (V)ertical: ... h
1 2 3
4 5 6 7
【未完】代碼沒有達到題目垂直排序的要求。需要補充。我奇怪的是,為什麼100個項的3列輸出是33+33+34而不是34+34+32。個人覺得後者比較合理一點。也較容易實現。