MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / get_transitions

Function get_transitions

graphs/markov_chain.py:41–78  ·  view source on GitHub ↗

Running Markov Chain algorithm and calculating the number of times each node is visited >>> transitions = [ ... ('a', 'a', 0.9), ... ('a', 'b', 0.075), ... ('a', 'c', 0.025), ... ('b', 'a', 0.15), ... ('b', 'b', 0.8), ... ('b', 'c', 0.05), ... ('c', 'a', 0.2

(
    start: str, transitions: list[tuple[str, str, float]], steps: int
)

Source from the content-addressed store, hash-verified

39
40
41def get_transitions(
42 start: str, transitions: list[tuple[str, str, float]], steps: int
43) -> dict[str, int]:
44 """
45 Running Markov Chain algorithm and calculating the number of times each node is
46 visited
47
48 >>> transitions = [
49 ... ('a', 'a', 0.9),
50 ... ('a', 'b', 0.075),
51 ... ('a', 'c', 0.025),
52 ... ('b', 'a', 0.15),
53 ... ('b', 'b', 0.8),
54 ... ('b', 'c', 0.05),
55 ... ('c', 'a', 0.25),
56 ... ('c', 'b', 0.25),
57 ... ('c', 'c', 0.5)
58 ... ]
59
60 >>> result = get_transitions('a', transitions, 5000)
61
62 >>> result['a'] > result['b'] > result['c']
63 True
64 """
65
66 graph = MarkovChainGraphUndirectedUnweighted()
67
68 for node1, node2, probability in transitions:
69 graph.add_transition_probability(node1, node2, probability)
70
71 visited = Counter(graph.get_nodes())
72 node = start
73
74 for _ in range(steps):
75 node = graph.transition(node)
76 visited[node] += 1
77
78 return visited
79
80
81if __name__ == "__main__":

Callers

nothing calls this directly

Calls 4

get_nodesMethod · 0.95
transitionMethod · 0.95

Tested by

no test coverage detected