形成魔方

时间:2018-08-18 17:13:07

标签: python magic-square

我们将魔方定义为从到的任意正整数矩阵,其中任何行,列或对角线长度的总和始终等于相同的数字:魔常数。

您将获得一个包含范围内的整数矩阵。我们可以将任何数字转换为范围内的任何其他数字,费用为。给定,以最小的成本将其转换为魔方。在新行上打印此费用。

注意:生成的幻方必须包含包含在内的不同整数。

例如,我们从以下矩阵开始:

5 3 4

1 5 8

6 4 2

我们可以将其转换为以下魔术方块:

8 3 4

1 5 9

6 7 2

这需要3次更换,费用为。 5-8 + 8-9 + 4-7 = 7

我已经编写了一个程序来解决这个问题,但是当我尝试运行它时却得到了错误的结果。

def formingMagicSquare(s):
    arr=[]
    duplicates=[]
    totaldifference=0
    for i in range(0,len(s)):
        linesum=sum(s[i])
        for j in range(0,len(s[i])):
            if(s[i][j] in arr and linesum!=15):
                duplicates.append(i*10+j)
            else:
                arr.append(s[i][j])
    for i in range(0,len(duplicates)):
        iarr = duplicates[i]//10
        jarr = duplicates[i]%10
        linesum=sum(s[i])
        difference=15-linesum
        totaldifference = totaldifference + difference
    return totaldifference

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = []

    for _ in range(3):
        s.append(list(map(int, input().rstrip().split())))

    result = formingMagicSquare(s)

    fptr.write(str(result) + '\n')

    fptr.close()

2 个答案:

答案 0 :(得分:0)

class Magic(object):

    pre = [
            [[8, 1, 6], [3, 5, 7], [4, 9, 2]],
            [[6, 1, 8], [7, 5, 3], [2, 9, 4]],
            [[4, 9, 2], [3, 5, 7], [8, 1, 6]],
            [[2, 9, 4], [7, 5, 3], [6, 1, 8]],
            [[8, 3, 4], [1, 5, 9], [6, 7, 2]],
            [[4, 3, 8], [9, 5, 1], [2, 7, 6]],
            [[6, 7, 2], [1, 5, 9], [8, 3, 4]],
            [[2, 7, 6], [9, 5, 1], [4, 3, 8]],
            ]

    def evaluate(self, s):
        totals = []
        for p in self.pre:
            total = 0
            for p_row, s_row in zip(p, s):
                for i, j in zip(p_row, s_row):
                    if not i == j:
                        total += max([i, j]) - min([i, j])
            totals.append(total)
        return min(totals)
def main():
    s=[]
    for _ in range(3):
        s.append(list(map(int, input().rstrip().split())))

    magic = Magic()
    result = magic.evaluate(s)

    print(result)

if __name__ == '__main__':
    main()

谢谢,我已经编写了新代码,并且已经从基础上更改了代码。

答案 1 :(得分:0)

我认为您可以轻松尝试:

def forming_magic_square(s):

    # Flaten s
    s = list(itertools.chain.from_iterable(s))

    magic_squares = [
        [8, 1, 6, 3, 5, 7, 4, 9, 2],
        [6, 1, 8, 7, 5, 3, 2, 9, 4],
        [4, 9, 2, 3, 5, 7, 8, 1, 6],
        [2, 9, 4, 7, 5, 3, 6, 1, 8],
        [8, 3, 4, 1, 5, 9, 6, 7, 2],
        [4, 3, 8, 9, 5, 1, 2, 7, 6],
        [6, 7, 2, 1, 5, 9, 8, 3, 4],
        [2, 7, 6, 9, 5, 1, 4, 3, 8],
    ]

    costs = []
    for magic_square in magic_squares:
        costs.append(sum([abs(magic_square[i] - s[i]) for i in range(9)]))

    return min(costs)