XML 1 - Find the Score

Sort by

recency

|

204 Discussions

|

  • + 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
  • + 0 comments

    in this challenge, root carry all the xml element as a string but with clarity of lines so if we iterate it using root.iter we iter each element or we say each line individualy afcourse it is done by using loop and in each iteration we use iterpointer(i) in loop and count the i.attrib because here this will give all attribute in form of dict and after that we find the len of that dict which have attribute and save it ,so now you will understand the logic behind this there are many functions of xml you can directly explore it using ai , python webpage and other ways above is my code-:

  • + 1 comment

    My version :

    import sys
    import xml.etree.ElementTree as etree
    
    def get_attr_number(root: etree)-> int:
        score=0
        
        for _ in root.attrib:
            score+=1
          
        for child in root:
            for _ in child.attrib:
                score+=1
            for sub_child in child:
                for _ in sub_child.attrib:
                    score+=1
            
        return score
            
    
    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

      Note : class the comments by votes and look at the first one. Displays a very much nicer solution based on the comprehension of the root.iter() method.

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