import random
def markov(probs, iter):
# normalize the probabilities
total = sum(probs)
probs = map(lambda e: float(e)/total, probs)
# determine the number of states
n = len(probs)
# Set the initial state
s = 0
for i in xrange(iter):
thresh = random.random()
buildup = 0
# When the sum of our probability vector is greater than `thresh`
# we've found the next state
for j in xrange(n):
buildup += probs[j]
if buildup >= thresh:
break
# Set the new state
s = j
return s
假设你有一个概率向量(而不是3),并且你的初始状态是第一个。在
因此
^{pr2}$但这只返回最后一个状态。不过,用一个巧妙的技巧很容易解决这个问题。让我们把它变成发电机。我们只需要再多写一行,
yield s
。在现在,当我们调用
markov
时,我们无法立即得到响应。在相反,我们得到一个
generator object
,它有点像“冻结”循环。您可以使用next
来执行一次甚至可以用
list
来放松整个过程相关问题 更多 >
编程相关推荐