Monday, February 21, 2011

Converting Python code to PHP

What is the following Python code in PHP?

import sys

li = range(1,777);

def countFigure(li, n):
        m = str(n);
        return str(li).count(m);

# counting figures
for substr in range(1,10):
        print substr, " ", countFigure(li, substr);

Wanted output for 777

1   258
2   258
3   258
4   258
5   258
6   258
7   231
8   147
9   147
From stackoverflow
  • It's been a while since I did any Python but I think this should do it. If you could clarify what str(li) looks like it would help.

    <?php
    
    $li = implode('', range(1, 776));
    
    function countFigure($li, $n)
    {
        return substr_count($li, $n);
    }
    
    // counting figures
    
    foreach (range(1, 9) as $substr)
        echo $substr, " ", countFigure($li, $substr), "\n";
    
    Greg : Thanks I've edited to correct

0 comments:

Post a Comment