Here are a few puzzling python code snippets and results that will put your knowledge of the inner workings of the language to the test. For each of them, see if you can figure out what code could have preceded what is written to produce the output or result indicated.
Do not overwrite built-in python types or functions
Do not define or redefine
__magic__methods or members
Do not circumvent execution of the code provided
Use python 2.7 (this is really more of a guideline)
If you think you have answers to one or more of these, leave a link to a gist or pastebin in the comments. Some of these have multiple solutions so bonus points are available for extra solutions to each one (Editor’s note: no actual points will be awarded).
def print_stuff(stuff): if stuff: print "Printing some stuff" for x in stuff: print x else: print "Nothing to print" print_stuff(mystery) # output: # Printing some stuff
def sum_numbers(low, high): total = 0 while low <= high: total += low low += 1 return total # Make sure we are using valid numeric values assert float('-inf') < mystery1 < float('inf') assert float('-inf') < mystery2 < float('inf') print sum_numbers(mystery1, mystery2) # result: # Program never terminates
# These are exactly dicts, not subclasses of dict assert type(mystery1) is dict assert type(mystery2) is dict print mystery1 == mystery2 # result: # RuntimeError: maximum recursion depth exceeded in cmp
assert type(mystery1) is dict assert type(mystery2) is dict assert str(mystery1) != str(mystery2) assert mystery1 == mystery2 print "All checks passed" # output: # All checks passed
Edit: Looks like I need to improve my proof-reading skills. I originally meant for line 5 to read as above, not
assert str(mystery1) == str(mystery2). Hopefully this clears up confusion about the last problem.