I figured I'd start a series of Python challenges in my blog. Whenever I've posted questions such as these in the past, the discussion that follows is always very entertaining!
A discussion arose today at work about the best way to flatten a tuple consisting of values and other tuples (which may be nested arbitrarily). So the tuple
(1, (1, 2, (1, 2, 3), 3)) would become
(1, 1, 2, 1, 2, 3, 3). Now there was actually code implemented which was functional, efficient and easy to read – but where is the fun in that?
I figured I could re-write it in a more terse manner, and here is what I came up with:
def flatten(tpl): return eval(repr(tpl).replace('(', '').replace(')', '')) t= (1, (1, 2, (1, 2, 3), 3)) print flatten(t)
flatten function would actually work in the context of our app, but I would never use it in production code. My challenge today, is to tell me why this code should never be used!