Python列表维度大小错误
考虑python中的以下代码:Python列表维度大小错误,python,list,Python,List,考虑python中的以下代码: def main(): n = input( ) s = input( ) coins = [ 0 ]*n dp = [ 0 ]*( s+1 ) print coins print dp for i in range( n ) : coins[ i ] = input( ) dp[ 0 ]=0 dp[ 1 ]=1 for i in range( 2, s+1
def main():
n = input( )
s = input( )
coins = [ 0 ]*n
dp = [ 0 ]*( s+1 )
print coins
print dp
for i in range( n ) :
coins[ i ] = input( )
dp[ 0 ]=0
dp[ 1 ]=1
for i in range( 2, s+1 ) :
min_val = 999999
for j in range( 0, n ) :
if i-coins[ j ] > 0 :
if dp[ i-coins[ j ] ] + 1 < min_val :
min_val = dp[ i-coins[ j ] ] + 1
print coins
print dp
print coins[ s ]
if __name__ == "__main__" :
main()
dp是s+1长度,但for循环变为n。如果s+1>n,则这将起作用。但在这种情况下,我认为你的s+1
dp = [ None ]*( s+1 ); # dp is s+1 in length.
for j in range( 0, n ) # loop goes to n.
列表索引超出范围意味着s+1if
)是i-coins[j]>0
,因此它必须大于或等于len(dp)
,即s+1
i
小于s+1
,因此硬币[j]
是负数
您是否为其中一枚硬币输入了负数?尝试使用
coins = [ 0 ]*n
dp = [ 0 ]*( s+1 )
初始化数组
我的机器上出现了完全不同的错误:
File "ttt.py", line 31, in <module>
main()
File "ttt.py", line 21, in main
if dp[ i-coins[ j ] ] + 1 < min_val :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
文件“ttt.py”,第31行,在
main()
文件“ttt.py”,第21行,主
如果dp[i-coins[j]+1<最小值:
TypeError:不支持+:“NoneType”和“int”的操作数类型
和print dp[s]
而不是print coins[s]
在最后一行。您不需要使用分号。它们只会增加噪音。既然你已经在上面一行中使用了coins[j]
,那就不可能了。请尝试打印该表达式的值。为什么要导入array
?你没有使用那个模块中的任何函数。@ MaTijnPixter我基本上是用C++编写的,所以我已经习惯了添加。我想你当时也对数组感到困惑。在代码中,您使用的是python列表,这很好,但不要将它们称为数组,也不需要导入array
模块。
coins = [ 0 ]*n
dp = [ 0 ]*( s+1 )
File "ttt.py", line 31, in <module>
main()
File "ttt.py", line 21, in main
if dp[ i-coins[ j ] ] + 1 < min_val :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'