Converting Python Code to PHP

前端 未结 6 1813
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 19:09

Is there a software converter out there that can automatically convert this python code to PHP?

#!/usr/bin/python
import math

def calcNumEntropyBits(s):
            


        
6条回答
  •  遥遥无期
    2021-01-01 20:11

    I'm not aware of any Python-to-PHP converter in the wild, but it should be a trivial task to port and the similarities are quite easy to spot:

    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');
    

    The last few lines in the first function could have also been written as a standard PHP ternary expression:

    return ($entropy >= 0.0)? 0.0: -($entropy*strlen($s));
    

提交回复
热议问题