简体   繁体   中英

python. How to calculate time complexity?

I have written this code that does the job i want it to. What I want to do is figure out the big O notation for the code. So I want to learn how to calculate the time complexity and end up with a big O notation result. How is it done in lay mans terms?

"""

def treetocode(hTree):

    code = dict()
    
    def getCode(hNode, currentcode=""):

        if (hNode == None): return
        if (hNode.left == None and hNode.right == None):
            code[hNode.char] = currentcode
        getCode(hNode.left, currentcode + "0")
        getCode(hNode.right, currentcode + "1")
        if hNode.char == None:
            return None
        else:
            print('Character = {}  :  Freq = {} --- Huffman code {}'.format(hNode.char, hNode.freq, currentcode))

    getCode(hTree)
    return code

"""

Time complexity is unrelated to the language you're using, unless your implementation causes the code to behave differently than the algorithm you have in mind. Since you came up with the algorithm, you can go over the usual steps used to figure out time complexity.

Run the program in your mind. How many times is the function called for every node of the tree? (or whatever structure you have).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM