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。个人觉得后者比较合理一点。也较容易实现。