python HackerRank“形成一个魔术广场”的python解决方案

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python HackerRank“形成一个魔术广场”的python解决方案相关的知识,希望对你有一定的参考价值。

import sys

# Solve https://www.hackerrank.com/challenges/magic-square-forming/problem
matrix_list = [[[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 get_min_cost(mat: list) -> int:
    cost_list = [sys.maxsize] * len(matrix_list)
    for ref_mat in matrix_list:
        cost = 0
        for x in range(0, len(mat)):
            for y in range(0, len(mat)):
                if mat[x][y] != ref_mat[x][y]:
                    cost += abs(mat[x][y] - ref_mat[x][y])
        cost_list.append(cost)
    return min(cost_list)


# s = [[4, 8, 2], [4, 5, 7], [6, 1, 6]]
# s = [[4, 4, 7], [3, 1, 5], [1, 7, 9]]
# s = [[7, 2, 9], [6, 6, 2], [5, 1, 2]]
s = []
for s_i in range(3):
    s_t = [int(s_temp) for s_temp in input().strip().split(' ')]
    s.append(s_t)
print(get_min_cost(s))

以上是关于python HackerRank“形成一个魔术广场”的python解决方案的主要内容,如果未能解决你的问题,请参考以下文章

Python Hackerrank挑战给出了〜stdout没有响应〜错误

python https://www.hackerrank.com/challenges/maximize-it/problem

堆栈和优化——来自hackerrank的例子

我如何在HackerRank上的此算术运算符问题中创建预期的输出?

调查了 71000 名开发者发现,JavaScript 最知名,Python 仍大势

hackerrank答案