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条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路