XML 2 - Find the Maximum Depth in Python - HackerRank Solution

XML 2 - Find the Maximum Depth in Python - HackerRank Solution  
XML2 - Find the Maximum Depth in Python - HackerRank Solution
 


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 N 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 : 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# XML2 - Find the Maximum Depth in Python - Hacker Rank Solution
# Python 3

import xml.etree.ElementTree as etree

maxdepth = 0
def depth(elem, level):
    global maxdepth
    # your code goes here
    # XML2 - Find the Maximum Depth in Python - Hacker Rank Solution START
    if (level == maxdepth):
        maxdepth += 1
    for child in elem:
        depth(child, level + 1)
    # XML2 - Find the Maximum Depth in Python - Hacker Rank Solution END

if __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)





Disclaimer :-
the above hole problem statement is given by hackerrank.com but the solution is generated by the codeworld19 authority if any of the query regarding this post or website fill the following contact form thank you.

Next Post Previous Post
No Comment
Add Comment
comment url