Question 23
Consider the following code that calls the modified magic function from the tutorial (qSort):
How many times will 'Abracadabra!' be printed?
Hint
Given the value lst = [22, 6, 18, 39, 1] as per how magic() is called, run through the function and then determine the final output of lsta + [pivot] + lstb.
Solution
Given inner variable lst = [22, 6, 18, 39, 1] as per calling magic([22, 6, 18, 39, 1]),
if not lst:False, sincelstis not empty. Skip if block'Abracadabra!'printedpivot = lst[0] = 22lstareturns output ofmagic()with list of elements inlstsmaller thanpivotmagic([6, 18, 1])\(\Rightarrow\)'Abracadabra!'printed;magic([1])\(\Rightarrow\)'Abracadabra!'printed;magic([])- return[]
- Hence,
magic([1])returns[] + [1] + [] = [1] magic([18])\(\Rightarrow\)'Abracadabra!'printed;magic([])- return[]
- Hence,
magic([18])returns[] + [18] + [] = [18]
- Hence,
magic([6, 18, 1])returns[1] + [6] + [8] = [1, 6, 18]
lstbreturns output ofmagic()with list of elements inlstlarger thanpivotmagic([39])\(\Rightarrow\)'Abracadabra!'printed;magic([])- return[]
- Hence,
magic([39])returns[] + [39] + [] = [39]
Hence, magic([22, 6, 18, 39, 1]) returns [1, 6, 18] + [22] + [39] = [1, 6, 18, 22, 39]
Notice that 'Abracadabra!' is printed each time magic() is called.
Right here, it can be inferred that magic() is recursively called a total of 4 times in addition to the 1 initial call, which is representative of the number of elements inside lst.
Answer
5