0

我正在尝试在 python 中制作一个程序来识别正方形是否是幻方,并且我无法将用户输入放入列表中。我知道我的代码可能会更有效率,但我对 python 很陌生。

column_1 = (0,3)
column_2 = (0,3)
column_3 = (0,3)
column_4 = (0,3)

row_1 = [int(i) for i in input('input row 1 with spaces inbetween numbers: ').split(' ')]
row_2 = [int(i) for i in input('input row 2 with spaces inbetween numbers: ').split(' ')]
row_3 = [int(i) for i in input('input row 3 with spaces inbetween numbers: ').split(' ')]
row_4 = [int(i) for i in input('input row 4 with spaces inbetween numbers: ').split(' ')]

column_1[0].append(row_1[0])
column_1[1].append(row_2[0])
column_1[2].append(row_3[0])
column_1[3].append(row_4[0])

column_2[0] = row_1[1]
column_2[1] = row_2[1]
column_2[2] = row_3[1]
column_2[3] = row_4[1]

column_3[0] = row_1[2]
column_3[1] = row_2[2]
column_3[2] = row_3[2]
column_3[3] = row_4[2]

column_4[0] = row_1[3]
column_4[1] = row_2[3]
column_4[2] = row_3[3]
column_4[3] = row_4[3]

diagonal_left_to_right[0] = column_1[0]
diagonal_left_to_right[1] = column_2[1]
diagonal_left_to_right[2] = column_3[2]
diagonal_left_to_right[3] = column_4[3]

diagonal_right_to_left[0] = column_4[0]
diagonal_right_to_left[1] = column_3[1]
diagonal_right_to_left[2] = column_2[2]
diagonal_right_to_left[3] = column_1[3]

sum_row_1 = sum(row_1)
sum_row_2 = sum(row_2)
sum_row_3 = sum(row_3)
sum_row_4 = sum(row_4)

sum_col_1 = sum(column_1)
sum_col_2 = sum(column_2)
sum_col_3 = sum(column_3)
sum_col_4 = sum(column_4)

sum_dag_l2r = sum(diagonal_left_to_right)
sum_dag_r2l = sum(diagonal_right_to_left)

if sum_row_1 == sum_row_2 == sum_row_3 == sum_row_4 == sum_col_1 == sum_col_2 == sum_col_3 == sum_col_4 == sum_dag_r2l == sum_dag_l2r:
    print('magic')

else:
    print('not magic')

我不断收到“int”对象没有“append”属性的错误消息。我尝试了很多在这个网站上找到的不同方法,但由于各种原因,它们都没有奏效。我对所有建议持开放态度,任何事情都会对我有所帮助。谢谢

4

1 回答 1

0

您首先定义column_1为元组(具有 2 个整数值,一个在索引 0 处,一个在索引 1 处)。该append方法行不通column_1[0],这就像做0.append()。您可能不打算创建一个元组,而是一个具有特定维度的列表。

您可以使用此列表表示法将值分配给列和对角线:

column_1 = [row_1[0], row_2[0], row_3[0], row_4[0]]
column_2 = [row_1[1], row_2[1], row_3[1], row_4[1]]
column_3 = [row_1[2], row_2[2], row_3[2], row_4[2]]
column_4 = [row_1[3], row_2[3], row_3[3], row_4[3]]
diagonal_left_to_right = [column_1[0],column_2[1],column_3[2],column_4[3]]
diagonal_right_to_left = [column_4[0],column_3[1],column_2[2], column_1[3]]
于 2017-10-13T18:42:10.900 回答