def ising_optimize(matrix) :
"""
Return the minimum value of E(x) with the matrix given as the input
parameter.
The matrix is provided either as a Python list-of-lists or as a
string which is the path to a CSV file.
"""
m = int(input('number of rows = '))
n = int(input('number of columns = '))
mat_x = []
for i in range(0,m): # initialize the number of rows
mat_x += [0]
for i in range (0,m): # initialize the matrix
mat_x[i] = [0]*n
for i in range (0,m):
for j in range (0,n):
print ('entry for row: ',i+1,'with column: ',j+1)
mat_x[i][j] = float(input())
print (mat_x)
W = [[0,1], [1, 0]]
flat_matrix_list = ([item for sublist in matrix for item in sublist])
print(flat_matrix_list)
sum = []
for w in range(len(flat_matrix_list)):
t=0
for x in range(len(mat_x)):
e = (w[0]*x[0]+w[1]*x[1]+w[2]*x[2]+w[3]*x[3])
t = -(e/2)
sum.append(t)
print(t)
return 0
答案 0 :(得分:0)
问题出在这段代码中:
for w in range(len(flat_matrix_list)):
t=0
for x in range(len(mat_x)):
e = (w[0]*x[0]+w[1]*x[1]+w[2]*x[2]+w[3]*x[3])
t = -(e/2)
sum.append(t)
在这里,w
和x
是整数。
编写w in range(len(flat_matrix_list))
时,在第一次迭代中w的值将为0,然后为1,2,...,直到数组的长度。而且您不能在整数上使用下标(例如w[0]
),这没有任何意义。
即使flat_matrix_list
数组本身的元素也是整数,所以按照@JohnGordon的答案使用for w in flat_matrix_list
也无济于事。
帮助我们,您到底想用这段代码做什么?
答案 1 :(得分:-1)
for w in range(len(flat_matrix_list)):
t=0
for x in range(len(mat_x)):
e = (w[0]*x[0]+w[1]*x[1]+w[2]*x[2]+w[3]*x[3])
w
和x
是单个整数。说w[0]
或x[2]
是没有道理的。
您是要说for w in flat_matrix_list:
吗?这可能是有道理的,因为w
将是该列表中的每个 item ,您可以对其进行子索引。