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.
-
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]) -
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) -
What does assert do? Is it the equivalent of throwing an Exception?
assert min(good_probs) > max(bad_probs) -
Python Pickle, is that essentially serialize?
pickle.dump({'mat': counts, 'thresh': thresh}, open('gib_model.pki', 'wb'))
Thanks for any help.
Edit: typos.
1. What is the PHP equivalent of yield?
There is no equivalent to
yieldin PHP.yieldis used in generator functions – a special class of function that returns a result but retains its state.For example:
You can do something similar in PHP like so:
2. What exactly is xrange?
xrangebehaves just likerange, 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.