XML2 - Find the Maximum Depth HackerRank Solution In Python

Problem

You are given a valid XML document, and you have to print the maximum level of nesting in it. Take the depth of the root as 0.

Input Format

The first line contains N, the number of lines in the XML document.
The next  lines follow containing the XML document.

Output Format

Output a single line, the integer value of the maximum level of nesting in the XML document.

Sample Input

6
<feed xml:lang='en'>
<title>HackerRank</title>
<subtitle lang='en'>Programming challenges</subtitle>
<link rel='alternate' type='text/html' href='http://hackerrank.com/'/>
<updated>2013-12-25T12:00:00</updated>
</feed>

Sample Output

1

Explanation

Here, the root is a feed tag, which has depth of 0.
The tags title, subtitle, link and updated all have a depth of 1.

Thus, the maximum depth is 1.

Solution – XML2 – Find the Maximum Depth in Python | HackerRank

import xml.etree.ElementTree as etreemaxdepth = 0def depth(elem, level):    global maxdepth    if len(list(elem)) > 0:        maxdepth += 1        lst = []        for el in elem:            if not el.tag in lst:                e = etree.ElementTree(etree.fromstring(etree.tostring(el))).getroot()                lst.append(el.tag)                if len(list(e)) > 0:                    depth(e, level)                else:                    pass    # your code goes hereif __name__ == '__main__':    n = int(input())    xml = ""    for i in range(n):        xml =  xml + input() + "\n"    tree = etree.ElementTree(etree.fromstring(xml))    depth(tree.getroot(), -1)    print(maxdepth)

Comments