您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将Python代码转换为PHP

将Python代码转换为PHP

我不知道在野外有任何Python到PHP的转换器,但是移植它应该是一件轻而易举的事,相似之处很容易发现:

function calcNumEntropyBits($s) {
        if (strlen($s) <= 0) return 0.0;
        $symCount = array();
        foreach (str_split($s) as $c) {
                if (!in_array($c,$symCount)) $symCount[$c] = 1;
                else $symCount[$c] ++;
        }
        $entropy = 0.0;
        foreach ($symCount as $c=>$n) {
                $prob = $n / (float)strlen($s);
                $entropy += $prob * log($prob)/log(2);
        }
        if ($entropy >= 0.0) return 0.0;
        else return -($entropy*strlen($s));
}

function testEntropy($s):
        printf("Bits of entropy in '%s' is %.2f",$s,calcNumEntropyBits($s));

testEntropy('hello world');
testEntropy('bubba dubba');
testEntropy('aaaaaaaaaaa');
testEntropy('aaaaabaaaaa');
testEntropy('abcdefghijk');

一个函数的最后几行也可以写成标准的PHP三元表达式:

return ($entropy >= 0.0)? 0.0: -($entropy*strlen($s));
php 2022/1/1 18:48:30 有301人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶