Saturday, December 28, 2024
Google search engine
HomeLanguagesPython Program for Markov matrix

Python Program for Markov matrix

Given a m x n 2D matrix, check if it is a Markov Matrix.
Markov Matrix: The matrix in which the sum of each row is equal to 1.

Example of Markov Matrix

Examples: 

Input :
1    0   0
0.5  0  0.5
0    0   1
Output : yes

Explanation :
Sum of each row results to 1, 
therefore it is a Markov Matrix.

Input :
1 0 0
0 0 2
1 0 0
Output :
no

Approach: Initialize a 2D array, then take another single dimensional array to store the sum of each rows of the matrix, and check whether all the sum stored in this 1D array is equal to 1, if yes then it is Markov matrix else not. 

Python3




# Python 3 code to check Markov Matrix
 
def checkMarkov(m) :
     
    # Outer loop to access rows
    # and inner to access columns
    for i in range(0, len(m)) :
         
        # Find sum of current row
        sm = 0
        for j in range(0, len(m[i])) :
            sm = sm + m[i][j]
 
        if (sm != 1) :
            return False
             
    return True
     
# Matrix to check
m = [ [ 0, 0, 1 ],
      [ 0.5, 0, 0.5 ],
      [ 1, 0, 0 ]      ]
 
# Calls the function check()
if (checkMarkov(m)) :
    print(" yes ")
else :
    print(" no ")
     
     
# This code is contributed by Nikita Tiwari.


Output

 yes 

Time Complexity: O(m*n), Here m is the number of rows and n is the number of columns.
Auxiliary Space: O(1), As constant extra space is used.

Please refer complete article on Program for Markov matrix for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
You’ll access excellent video content by our CEO, Sandeep Jain, tackle common interview questions, and engage in real-time coding contests covering various DSA topics. We’re here to prepare you thoroughly for online assessments and interviews.
Ready to dive in? Explore our free demo content and join our DSA course, trusted by over 100,000neveropen! Whether it’s DSA in C++, Java, Python, or JavaScript we’ve got you covered. Let’s embark on this exciting journey together!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments