ProgrammingVery hardWipro · Accenture · Capgemini pattern
What does the following Python 3 code print? class Stack: def __init__(self): self._items = [] def __len__(self): return len(self._items) def __bool__(self): return len(self._items) > 0 def push(self, x): self._items.append(x) s = Stack() print(bool(s)) s.push(1) print(bool(s), len(s))
- A. False False 1
- B. True True 1
- C. False True 1
- D. False True 0
Correct answer: C. False True 1
bool() calls __bool__ which checks the underlying list; empty gives False, and after one push it has length 1, so bool is True.
More Python Programming questions
- What does the following Python 3 code print? class Range2: def init(self, n): self.n = n def getitem(self, i): if i >= self.n: raise…
- What does the following Python 3 code print? import itertools print(list(itertools.chain.fromiterable([[1, 2], [3], [4, 5, 6]])))
- What does the following Python 3 code print? import itertools print(list(itertools.product([1, 2], [3, 4])))
- What does the following Python 3 code print? import itertools print(list(itertools.combinationswithreplacement([1, 2, 3], 2)))
- What does the following Python 3 code print? import itertools print(list(itertools.compress([1, 2, 3, 4, 5], [1, 0, 1, 0, 1])))
- What does the following Python 3 code print? import itertools print(list(itertools.dropwhile(lambda x: x < 3, [1, 2, 3, 4, 1, 2])))