XML 1 - Find the Score

Sort by

recency

|

208 Discussions

|

  • + 0 comments
    import sys
    import xml.etree.ElementTree as etree
    
    def get_attr_number(node):
        return sum(len(elem.attrib) for elem in node.iter())
    
    if __name__ == '__main__':
        sys.stdin.readline()
        xml = sys.stdin.read()
        tree = etree.ElementTree(etree.fromstring(xml))
        root = tree.getroot()
        print(get_attr_number(root))
    
  • + 0 comments

    I don't know why, but I was pretty sure that we have to do recursive method to solve this problem. I mean, I did that, and it works. But when I see others solutions, I have seen that node.iter() just go through every line of the xml document which is, I think, better.

    Anyway, here my code :

    import sys
    import xml.etree.ElementTree as etree
    
    def get_attr_number(node):
        # your code goes here
        count = len(node.attrib)
               
        for child in node:
            count += get_attr_number(child)
            
        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))
    
  • + 0 comments

    Here is HackerRank XML 1 - Find the Score in Python solution - https://programmingoneonone.com/hackerrank-xml-1-find-the-score-solution-in-python.html

  • + 0 comments
    import sys
    import xml.etree.ElementTree as etree
    
    def get_attr_number(node):
        count = len(node.attrib)
        for child in node:
            count += get_attr_number(child)
        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))
    
  • + 0 comments
    1. def get_attr_number(node):
    2. count = 0
    3. for i in node.iter():
    4. count+=len(i.attrib)
    5. return count