感觉题目描述不是很具体,看样例输入可知先左边切割数字,在下面,右边,上面,如此循环,像逆时针画圈般。
在做这个题目时,主要解决几个问题:1. python 输入多行数据,空格隔开 2.判断二维数组是否为空,这个有点tricky,大家可以写小代码测试下。这个问题涉及到要怎么更好的删除数据。注意考虑数组只有一列的时候的删除情况。 3. 题目要求输出一串数字,别直接输出列表了:)
下面是写的测试小代码:
str = [[7], [9], [2]]
for i in range(len(str)):
del str[i][0]
print(str)
if str is None:
print('str is None')
else:
print('str is not None')
str = [[7], [9], [2]]
for i in range(len(str)):
del str[i]
print(str)
if str is None:
print('str is None')
else:
print('str is not None')
str = [[7], [9], [2]]
for i in range(len(str)):
del str[0]
print(str)
if str is None:
print('str is None')
else:
print('str is not None')
下面上代码,本人水平有限,写的不好的地方,还请大家指正,一起学习~
# 回文取数
# m rows n columns
m, n = map(int, input().split())
huiwen = [[None]*n for i in range(m)]
str = []
for i in range(m):
huiwen[i] = list(map(int, input().split()))
while True:
# left
if huiwen:
if len(huiwen[0]) == 1:
for i in range(len(huiwen)):
str.append(huiwen[0][0])
del huiwen[0]
else:
for i in range(len(huiwen)):
str.append(huiwen[i][0])
del huiwen[i][0]
# bottom
if huiwen:
str += huiwen[-1]
huiwen.pop()
# right
if huiwen:
s = len(huiwen)
if len(huiwen[0]) == 1:
for i in range(s):
str.append(huiwen[s-i-1][0])
del huiwen[s-i-1]
else:
for i in range(s):
str.append(huiwen[s-i-1][-1])
del huiwen[s-i-1][-1]
# up
if huiwen:
huiwen[0].reverse()
str += huiwen[0]
huiwen.pop(0)
if not huiwen:
for i in range(m*n):
print(str[i], end=' ')
exit()