【发布时间】:2019-07-09 03:29:41
【问题描述】:
我是一名热爱编程的本科生。我今天遇到一个问题,我不知道如何解决这个问题。 我寻找“Python - 字符串到矩阵表示”(Python - string to matrix representation)寻求帮助,但我仍然对这个问题感到困惑。
问题出在以下几点:
给定一串空格分隔的数字,创建一个 nxn 矩阵(一个二维列表,其中列数与行数相同)并返回它。该字符串将包含整数的完美平方数。 int() 和 split() 函数可能很有用。
例子:
输入:'1 2 3 4 5 6 7 8 9'
输出:[[1,2,3],[4,5,6],[7,8,9]]
示例 2:
输入:'1'
输出:[[1]]
我的回答:
import numpy as np
def string_to_matrix(str_in):
str_in_split = str_in.split()
answer = []
for element in str_in_split:
newarray = []
for number in element.split():
newarray.append(int(number))
answer.append(newarray)
print (answer)
测试结果如下:
Traceback (most recent call last):
File "/grade/run/test.py", line 20, in test_whitespace
self.assertEqual(string_to_matrix('1 2 3 4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]
Stdout:
[[4]]
还有
Traceback (most recent call last):
File "/grade/run/test.py", line 15, in test_small
self.assertEqual(string_to_matrix('1 2 3 4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]
Stdout:
[[4]]
还有
Traceback (most recent call last):
File "/grade/run/test.py", line 10, in test_one
self.assertEqual(string_to_matrix('1'), [[1]])
AssertionError: None != [[1]]
Stdout:
[[1]]
还有
Traceback (most recent call last):
File "/grade/run/test.py", line 25, in test_larger
self.assertEqual(string_to_matrix('4 3 2 1 8 7 6 5 12 11 10 9 16 15 14 13'), [[4,3,2,1], [8,7,6,5], [12,11,10,9], [16,15,14,13]])
AssertionError: None != [[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]]
Stdout:
[[13]]
我仍然很困惑如何解决这个问题。非常感谢您的帮助!
【问题讨论】:
-
assertEqual 不会比较您的
print结果,它使用 string_to_matrix 返回的值。 string_to_matrix 当前不返回任何内容,因此值为 None。更改return的打印,您将开始获得更好的结果 -
首先,您创建的函数仅
print给出答案,而不是return,因此断言将始终失败,因为None是函数默认返回的。将print (answer)替换为简单的return answer。其次,您似乎没有考虑到“字符串将包含整数的完美平方数”。
标签: python python-3.x numpy