Thamizhiniyan C S
HomeWriteupsResourcesCheatsheets
HackerRank
HackerRank
  • HackerRank
  • Linux Shell
    • Bash
    • Text Processing
      • Cut
      • Head
      • Middle
      • Tail
      • Tr
      • Sort
      • Uniq
      • Paste
    • Arrays In Bash
    • Grep Sed Awk
      • Grep
      • Sed
      • Awk
  • Regex
    • Introduction
    • Character Class
    • Repetitions
    • Grouping and Capturing
    • Backreferences
    • Assertions
    • Applications
  • Python
    • Introduction
    • Basic Data Types
    • Strings
    • Sets
    • Math
    • Itertools
    • Collections
    • Date and Time
    • Errors and Exceptions
    • Classes
    • Built-Ins
    • Python Functionals
    • Regex and Parsing
    • XML
    • Closures and Decorators
    • Numpy
    • Debugging
  • C
    • Introduction
    • Conditionals and Loops
    • Arrays and Strings
Powered by GitBook
On this page
  • XML 1 - Find the Score
  • XML 2 - Find the Maximum Depth

Was this helpful?

  1. Python

XML

PreviousRegex and ParsingNextClosures and Decorators

Last updated 1 year ago

Was this helpful?

XML 1 - Find the Score

import sys
import xml.etree.ElementTree as etree

def get_attr_number(node):
    count = len(node.attrib)

    for each in node:
        if len(each) > 1:
            for i in each:
                count += len(i.attrib)
        else:
            count += len(each.attrib)

    return count


if __name__ == '__main__':
    sys.stdin.readline()
    xml = sys.stdin.read()
    tree = etree.ElementTree(etree.fromstring(xml))
    root = tree.getroot()
    print(get_attr_number(root))

XML 2 - Find the Maximum Depth

import xml.etree.ElementTree as etree

maxdepth = 0
def depth(elem, level):
    global maxdepth

    level += 1

    if level > maxdepth:
        maxdepth = level

    for each in elem:
        depth(each, level)

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)
Solve Programming Questions | HackerRankHackerRank
Logo