technology

Challenge Your Python Knowledge

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.

Suggested rules:

  • 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.


Discussion

8 responses to ‘Challenge Your Python Knowledge

  1. including the 4th one.

    All except the 3rd problem can be solved by creating a class that cleverly overwrites the magic methods. I really liked tylers approach for the float comparision 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s