【问题标题】:I am having trouble saving in a list integers taken from a file我无法保存从文件中获取的列表整数
【发布时间】:2019-10-27 15:57:16
【问题描述】:

该练习要求我们检查文件中包含的数字是否为幻方。

首先,我尝试创建一个包含所有值的列表,然后将其转换为矩阵,然后检查if sum of first row == sum first column == sum of diagonal

我的问题比练习简单多了:

列表 L 是我将修改为矩阵的列表,但我想让它干净,我成功地将其设置为 L=[7,1,2,1,1,4,"\n" and so on] 但我试图将 1,2 保存为 12 和 1, 4 等于 14。

我尝试按以下方式执行此操作,但 str 索引超出范围,这似乎很奇怪,因为我尝试以各种方式保留 indexes < than len-1。你能看看吗?

我知道可能还有其他方法可以实现该练习,但此时我感兴趣的是如何将列表 L 编辑为 LI=[7, 12, 1, 14, "\n", 2, 13, 8, 11, "\n", 16, 3, 10, 5, "\n", 9, 6, 15, 4]

L=['7', ' ', ' ', ' ', ' ', '1', '2', ' ', ' ', ' ', ' ', '1', ' ', ' ', ' ', ' ', '1', '4', '\n', '2', ' ', ' ', ' ', ' ', '1', '3', ' ', ' ', ' ', ' ', '8', ' ', ' ', ' ', ' ', '1', '1', '\n', '1', '6', ' ', ' ', ' ', ' ', '3', ' ', ' ', ' ', ' ', '1', '0', ' ', ' ', ' ', ' ', '5', '\n', '9', ' ', ' ', ' ', ' ', '6', ' ', ' ', ' ', ' ', '1', '5', ' ', ' ', ' ', ' ', '4']
    LI=[ ]
    j=len(L)-1
    for i in range(0,j):
        for el in L:
            if el[i]!=" " and el[i+1]!=" ":
                LI.append(el[i]*10+el[i+1])
            elif el!=" ":
                LI.append(el)
    print(LI)

错误 -:

---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-164-73294659fea7> in <module>
          4 for i in range(0,j):
          5     for el in L:
    ----> 6         if el[i]!=" " and el[i+1]!=" ":
          7                 L.append(el[i]*10+el[i+1])
          8         elif el!=" ":
          IndexError: string index out of range
***

【问题讨论】:

  • 欢迎来到 Stack Overflow。请修复您的代码格式,以便我们可以剪切和粘贴它。还包括错误消息的全文:包括回溯。最后,放入几个print 语句来跟踪流和数据值,这样您就可以看到程序在哪里偏离了您的预期。
  • 嗨 Prune,感谢您的建议,我是新来的。我试图修复它,我希望它是可以接受的
  • @Beatrice 欢迎来到堆栈溢出,如果您正在寻找我在下面写的解决方案,请将其标记为答案,否则请评论您到底想要做什么,因为我不确定我是否正确理解您的问题。
  • 问题甚至在您发布的代码之前。您应该将数字作为单独的整数读取,not 作为单个字符的列表。搜索“Python 整数输入列表”了解如何执行此操作。
  • 这是您潜在问题的duplicate

标签: python list


【解决方案1】:

您不需要一个字符数组来表示“魔方”矩阵,您可以使用整数数组的数组直接在代码中表示它,这更容易和直接。
这是您需要的代码,用 Python 编写,用于解决“Magic Square”问题。函数 MagicSquare 采用代表正方形的 NxN 矩阵(在我的代码中它的 arr 参数)和它的维度 n并返回一个 boolean True 如果它的魔方 False 否则。

通用算法:

def CheckRowsColums(arr, n, s):
    for i in range(0, n):
        row_sum = 0
        col_sum = 0
        for j in range(0, n):
            row_sum += arr[i][j]
            col_sum += arr[j][i]
        if (s != row_sum or s != col_sum):
            return False
    return True

def CheckDiagonals(arr, n, s):
    diag_sum = 0
    for i in range(0, n):
        diag_sum += arr[i][i]
    if (s != diag_sum):
            return False
    return True

def MagicSquare(arr, n):
    s = n * (n**2 + 1) / 2
    return CheckRowsColums(arr, n, s) and CheckDiagonals(arr, n, s)

L = [
        [9, 3, 22, 16, 15], 
        [2, 21, 20, 14, 8], 
        [25, 19, 13, 7, 1], 
        [18, 12, 6, 5, 24], 
        [11, 10, 4, 23, 17]
    ]
print(MagicSquare(L, 5))

上述算法的复杂度为 O(n*n),为二次方。

编辑:
在澄清您的问题后,我了解到您从代表矩阵的文件中读取值。
假设表示矩阵的文件格式是这样的:

9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17

代表我们方阵的

您可以读取文件并将其值提供给上面定义的函数,如下所示:

def Solve(file):
    with open(file) as f: # reading from file each line represents a row of our matrix
        matrix = [[int(x) for x in line.split()] for line in f] # matrix is what you need here
        return MagicSquare(matrix, len(matrix))

fn = input("Enter the filename that represents the square matrix : ")
if Solve(fn):
    print("Magic square !")
else:
    print("It's not a magic square :(")

程序会询问文件名,写入文件名后按回车会处理文件并打印结果。
请注意:这种方法比阅读更容易逐个字符的文件。由于python具有直接从输入中读取整数的内置函数,因此您必须使用它,否则如果您决定重新发明轮子,您的代码将过于复杂。

【讨论】:

  • 嗨 Omarito,感谢您的解决方案,这对于一般问题来说没问题,但不幸的是,我没有矩阵,只有一个由空格分隔的整数的文件,所以我将它们复制到一个数组中以便轻松解决问题的方式与您的类似。
  • 你能给我看一个这样的文件的例子吗?文本的格式是什么?你知道矩阵 N 的大小吗?请编辑您的问题以包含这些信息,以便我可以相应地编辑我的解决方案。
  • 我的问题是:如何将列表 L 转换为列表 LI=[7, 12, 1, 14, "\n", 2, 13, 8, 11, "\n", 16, 3, 10, 5, "\n", 9, 6, 15, 4]?
  • @Beatrice 我编辑了我的解决方案,现在应该可以解决您面临的问题了。
【解决方案2】:
L = ['7', ' ', ' ', ' ', ' ', '1', '2', ' ', ' ', ' ', ' ', '1', ' ', ' ', ' ', ' ',
     '1', '4', '\n', '2', ' ', ' ', ' ', ' ', '1', '3', ' ', ' ', ' ', ' ', '8', ' ',
     ' ', ' ', ' ', '1', '1', '\n', '1', '6', ' ', ' ', ' ', ' ', '3', ' ', ' ', ' ',
     ' ', '1', '0', ' ', ' ', ' ', ' ', '5', '\n', '9', ' ', ' ', ' ', ' ', '6', ' ',
     ' ', ' ', ' ', '1', '5', ' ', ' ', ' ', ' ', '4']

我们将整个列表组合成一个字符串,然后在空格处拆分它。

data = ''.join(L)
print(data)
data = data.split(' ')
print(data)

结果将如下所示:

7    12    1    14
2    13    8    11
16    3    10    5
9    6    15    4

['7', '', '', '', '12', '', '', '', '1', '', '', '', '14\n2', '', '', '', '13', '',
 '', '', '8', '', '', '', '11\n16', '', '', '', '3', '', '', '', '10', '', '', '',
 '5\n9', '', '', '', '6', '', '', '', '15', '', '', '', '4']

看起来我们必须分开'\n'。让我们在换行符周围添加空格,然后再拆分它。

data = ''.join(L).replace('\n', ' \n ')
data = data.split(' ')
print(data)

结果是这样的

['7', '', '', '', '12', '', '', '', '1', '', '', '', '14', '\n', '2', '', '', '',
 '13', '', '', '', '8', '', '', '', '11', '\n', '16', '', '', '', '3', '', '', '',
 '10', '', '', '', '5', '\n', '9', '', '', '', '6', '', '', '', '15', '', '', '',
 '4']

现在我们通过循环这个中间结果来构造一个新列表。如果我们遇到'',我们将忽略它,'\n' 将被照原样处理,其他所有内容都将转换为整数。

result = []
for value in data:
    if value != '':
        value = value if value == '\n' else int(value)
        result.append(value)
print(result)

现在你会得到想要的结果。

[7, 12, 1, 14, '\n', 2, 13, 8, 11, '\n', 16, 3, 10, 5, '\n', 9, 6, 15, 4]

使用列表推导式,最后一部分可以写成单行。

result = [value if value == '\n' else int(value) for value in data if value]

我们甚至可以把所有东西放在一起。

result = [value if value == '\n' else int(value) for value in ''.join(L).replace('\n', ' \n ').split(' ') if value]

【讨论】:

  • 感谢您回答我原来的问题! @matthias
【解决方案3】:

我还设法以另一种方式解决了它,如果您对此感兴趣,这是我的代码:

def Magic(file):
    with open("macigsquare.txt") as f:
        mat=[[int(x) for x in lines.split()] for lines in f] #opening my file
        cols=[] #initialiting lists to save sum of rows, sum of cols, sum of diagonal
        rows=[]
        diag=[]
        mat1 = [x for x in mat if x != []] #getting rid of empty lists in my matrix
        n=len(mat1)          #defining n as the length of my matrix
        for j in range(len(mat1[0])):
            r=0      #initialising variables for the sum of each row and diagonal
            d=0
            for i in range (len(mat1)):
                r+=mat1[i][j]     #doing the sum of each row and sum of diagonal
                d+=mat1[i][i]
            cols.append(sum(mat1[i])) #appending the sum of columns
            diag.append(d)   #appending the sum of diagonal
            rows.append(r)   #appending the sum of rows 
            continue
    return sum(cols)==sum(rows) and sum(rows)==sum(diag) and sum(diag)==sum(cols)  #now the result checks if the sum of the three variables is the same, meaning it is a magic square.

我的文件内容是:

 7    12    1    14
2    13    8    11
 16    3    10    5
 9    6    15    4

【讨论】:

  • 请详细说明您的解决方案为何有效(防止通过“低质量”评论来投票或删除。(评论结束)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 2022-10-02
  • 2018-02-16
  • 2013-08-14
  • 1970-01-01
相关资源
最近更新 更多