Converting Markov Chain Python Script to PHP. Not sure of what some of the equivalent functions are in PHP

StackOverflow https://stackoverflow.com/questions/7885761

  •  11-02-2021
  •  | 
  •  

Pregunta

I've seen this Markov Chain gibberish detector written in response to another question on Stackoverflow and I would like to convert it to PHP, I'm not looking for someone to do this for me, but I am confused over portions of the Python code that I have no knowledge of. I've looked at the python docs but it confuses me even further.

  1. What is the PHP equivalent of yield?

    def ngram(n, l):
    """ Return all n grams from l after normalizing """
    filtered = normalize(l)
    for start in range(0, len(filtered) - n + 1):
        yield ''.join(filtered[start:start + n])
    
  2. What exactly is xrange? There is a PECL extension, however I would prefer a pure PHP implementation? Would this be possible?

    counts = [[10 for i in xrange(k)] for i in xrange(k)]
    
    for i, row in enumerate(counts):
    s = float(sum(row))
    for j in xrange(len(row)):
        row[j] = math.log(row[j] / s)
    
  3. What does assert do? Is it the equivalent of throwing an Exception?

    assert min(good_probs) > max(bad_probs)
    
  4. Python Pickle, is that essentially serialize?

    pickle.dump({'mat': counts, 'thresh': thresh}, open('gib_model.pki', 'wb'))
    

Thanks for any help.


Edit: typos.

¿Fue útil?

Solución

1. What is the PHP equivalent of yield?

There is no equivalent to yield in PHP. yield is used in generator functions - a special class of function that returns a result but retains its state.

For example:

def simple_generator(start=0, end=100):
    while start < end:
        start += 1
        yield start
gen = simple_generator()
gen() # 1
gen() # 2
gen() # 3

You can do something similar in PHP like so:

class simple_generator {
    private $start;
    private $end;
    function __construct($start=0, $end=100) {
        $this->start = $start;
        $this->end = $end;
    }
    function __call() {
        if($this->start < $this->end) {
            $this->start++;
            return $start;
        }
    }
}
gen = simple_generator();
gen(); // 1
gen(); // 2

2. What exactly is xrange?

xrange behaves just like range, but uses a generator function. This is a performance tweak for working with very large lists or when memory is tight.

3. What does assert do? Is it the equivalent of throwing and Exception?

Yes. Beware - it is not the same as PHP's assert - which is a really fun vector for attacks on your software.

4. Python Pickle, is that essentially serialize?

Yes.

Otros consejos

  1. xrange returns an iterator. This is different from range which returns a list. Both behave mostly in the same fashion so just use it like you use range.

  2. Yes

  3. Yes

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top