You are given a valid XML document, and you have to print its score. The score is calculated by the sum of the score of each element. For any element, the score is equal to the number of attributes it has.
XML 1 - Find the Score - Hacker Rank Solution
PENDING (IF YOU KNOW PLEASE DROP A COMMENT :P)
#use this code
ReplyDeleteimport sys
import xml.etree.ElementTree as etree
def get_attr_number(node):
score = len(node.attrib)
for element in node.findall('.//*'):
score += len(element.attrib)
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))
import sys
ReplyDeleteimport xml.etree.ElementTree as etree
k=[]
def get_attr_number(node):
for elem in node.iter():
k.append(len(elem.attrib))
return sum(k)
#return sum([len(elem.items()) 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))
how to read xml files in python
Delete