ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Node:
def __init__(self, val, children=None):
self.val = val
self.children = children if children is not None else []
n1 = Node(1)
n2 = Node(2)
n1.children.append(n2)
print(len(Node(3).children))- A. 0
- B. 1
- C. 2
- D. AttributeError
Correct answer: A. 0
Using the None-sentinel pattern gives every instance that omits children its OWN fresh empty list; appending to n1.children never affects a brand-new Node(3), whose children list starts empty, length 0.
More Python Programming questions
- What does the following Python 3 code print? lst = [x x for x in range(5)] gen = (x x for x in range(5)) print(type(lst), type(gen))
- What does the following Python 3 code print? a = [1, 2, 3] b = a b.append(4) print(a)
- What does the following Python 3 code print? a = [1, 2, 3] b = a[:] b.append(4) print(a, b)
- What does the following Python 3 code print? def f(a, b, args): return a, b, args print(f(1, 2, 3, 4, 5))
- What does the following Python 3 code print? def f(kwargs): return sorted(kwargs.items()) print(f(b=2, a=1, c=3))
- What does the following Python 3 code print? def f(a, , b): return a + b try: print(f(1, 2)) except TypeError: print("err")