我正在浏览Peter Norvig的Sudoku求解器代码(http://norvig.com/sudopy.shtml)并且遇到了这一行:
peers = dict((s, set(sum(units[s],[]))-set([s]))
for s in squares)
如果我将代码复制到并包含此行(即直到第28行),并从文件中运行它,它运行正常,字典'peers'具有例外值。但是,如果在运行此文件后,我尝试从shell运行此行,我收到错误:
peers = dict((s, set(sum(units[s],[]))-set([s]))
for s in squares)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-33-2652de1ecd8a> in <module>()
1 peers = dict((s, set(sum(units[s],[]))-set([s]))
----> 2 for s in squares)
<ipython-input-33-2652de1ecd8a> in <genexpr>((s,))
1 peers = dict((s, set(sum(units[s],[]))-set([s]))
----> 2 for s in squares)
C:\PyCanopy\User\lib\site-packages\numpy\core\fromnumeric.pyc in sum(a, axis, dtype, out, keepdims)
1717 except AttributeError:
1718 return _methods._sum(a, axis=axis, dtype=dtype,
-> 1719 out=out, keepdims=keepdims)
1720 # NOTE: Dropping the keepdims parameters here...
1721 return sum(axis=axis, dtype=dtype, out=out)
C:\PyCanopy\User\lib\site-packages\numpy\core\_methods.pyc in _sum(a, axis, dtype, out, keepdims)
30
31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
---> 32 return umr_sum(a, axis, dtype, out, keepdims)
33
34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
TypeError: cannot perform reduce with flexible type
我无法理解为什么会这样。我发现这行代码很奇怪,因为它有一个sum
超过dict
键的值加上一个空[]
。任何指导?感谢。
答案 0 :(得分:3)
该代码适用于python
解释器和ipython
。
看起来在运行代码之前你做了这个:
from numpy import sum
所以现在sum
不是python的标准sum
,但它是从numpy
导入的不同函数。
这就是代码引发错误的原因。
解决方案:只需退出ipython
shell,再次运行并将代码粘贴到其中。
编辑:关于带有空列表的总和,这只是使单位[s]平坦的技巧。 例如,单位[&#39; I1&#39;]如下所示:
[['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1'],
['I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9'],
['G1', 'G2', 'G3', 'H1', 'H2', 'H3', 'I1', 'I2', 'I3']]
sum(units['I1'], [])
看起来像这样:
['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9', 'G1', 'G2', 'G3', 'H1', 'H2', 'H3', 'I1', 'I2', 'I3']
引擎盖下的总和是这样的:
list = []
for elem in units['I1']:
list = list + elem