0
0
Intro to Computingfundamentals~10 mins

Trees and hierarchical data in Intro to Computing - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a root node named 'root' in a simple tree structure.

Intro to Computing
class Node:
    def __init__(self, value):
        self.value = value
        self.children = []

root = Node([1])
Drag options to blanks, or click blank then click option'
A"root"
Broot
CNode
Dchildren
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string value.
Using variable names instead of string literals.
2fill in blank
medium

Complete the code to add a child node named 'child1' to the root node's children list.

Intro to Computing
child1 = Node("child1")
root.children.[1](child1)
Drag options to blanks, or click blank then click option'
Aappend
Bextend
Cinsert
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using add which is not a list method.
Using extend which expects an iterable, not a single item.
3fill in blank
hard

Fix the error in the code to correctly print all child node values of the root.

Intro to Computing
for child in root.children:
    print(child.[1])
Drag options to blanks, or click blank then click option'
Aname
Bchildren
Cvalue
Dchild
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to print child.children which is a list, not the name.
Using child.name which is not defined.
4fill in blank
hard

Fill both blanks to create a dictionary mapping each child's name to the number of its children.

Intro to Computing
child_counts = {child.[1]: len(child.[2]) for child in root.children}
Drag options to blanks, or click blank then click option'
Avalue
Bchildren
Cname
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using name instead of value for the child's name.
Using count which is not an attribute.
5fill in blank
hard

Fill all three blanks to create a dictionary of grandchildren counts for each child node with more than zero grandchildren.

Intro to Computing
grandchild_counts = {child.[1]: sum(len(grandchild.[2]) for grandchild in child.[3]) for child in root.children if sum(len(grandchild.children) for grandchild in child.children) > 0}
Drag options to blanks, or click blank then click option'
Avalue
Bchildren
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up keys and values in the dictionary comprehension.
Using incorrect attribute names like count or name.