doqp87012 2009-11-07 18:20
浏览 72
已采纳

找到将Python代码转换为PHP的逻辑错误

The input 7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4 returns 0 by the PHP -code, while 1 by Python code: 1 means that the sums of the 4x4 magic square are the same, while 0 means the reverse. Python code is correct.

The problem of the PHP code seems to be in the function divide's for -loop, since PHP gives too many sums.

How does the logic of PHP code differ from Python's?

PHP

$data = "7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4";
$array = explode("|", $data);

# Calculate the unique sums of the four figures
# @return array int
function divide ( $array ) {
        $sum = array_map('array_sum', array_chunk($array, 4));
        $apu_a = array();
        for ( $i = 0; $i < count( $sum ); $i++ ) {
                if ( $i % 5 == 0 )
                        $apu_a []= $array[$i];
        }
        $sum []= array_sum( $apu_a );

        $apu_a = array();
        for ( $i = 0; $i < count( $sum ); $i++ ) {
                if ( $i % 3 == 0 and $i != 15 and $i != 0 )
                        $apu_a []= $array[$i];
        }
        $sum []= array_sum( $apu_a );

        $result = array_unique($sum);
        return $result;
}

Python

data = "7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4"
lista = map(int,data.split("|"))

def divide( lista ):
        summat = [sum(lista[i:i+4]) for i in range(0,len(lista),4)]
        summat += [sum(lista[0::5]) for i in range(0, len(lista), 16)]
        summat += [sum(a for i,a in enumerate(lista) if i %3==0 and i != 15 and i != 0)]
        return set(summat)
  • 写回答

3条回答 默认 最新

  • doutao6330 2009-11-07 18:52
    关注

    The problem is in your PHP line:

    for ( $i = 0; $i < count( $sum ); $i++ ) {
    

    you wanted:

    for ( $i = 0; $i < count( $array ); $i++ ) {
    

    Fix it in both places, and you get the right answer.

    BTW: You are only checking the main diagonals, but you can also check the other wrapping diagonals, and as Greg points out, you never sum the columns.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在