Nothing this simple would ever require us to destroy the list inputs (or copy them), so pop
is out of the question.
Mind, if the lists themselves are disposable (meaning the globals that were passed in) then pop
is the perfect way to destroy them.
u, v = 0, 0
while a: u += a.pop()
while b: v += b.pop()
return u if u > v else v
The return line is Pythonās version of a ternary expression. Gloss over this if it is out of the purview. It will come up eventually when you study conditional expressions in greater detail.
Structures take up memory, however small. Nothing takes up less memory than None
, as I understand. That means that if we are truly destroying the data structures and recovering as much memory as possible, we can, in this function, obliterate them.
u, v = 0, 0
while a: u += a.pop()
while b: v += b.pop()
a, b = None, None
return u if u > v else v
edit
Take that back. We need to connect to the global variables to be able eliminate the data structure, itself.
>>> m, n = [2, 5, 8], [3, 6, 9]
>>> def bar():
global m, n # says we are going to be setting
u, v = 0, 0
while m: u += m.pop() # mutate
while n: v += n.pop() # mutate
m, n = None, None # set
return u if u > v else v
>>> bar()
18
>>> m, n
(None, None)
>>>
Although. del
comes to mind. Perfect garbage collection tool. Why would we ever give a function this much sway over our data structures?