Created
April 29, 2016 14:08
-
-
Save danob-jana/ab03f419bfdf8708ef08b4c18a552d4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# my solutions to https://technology.jana.com/2016/04/26/challenge-your-python-knowledge/ | |
def challenge_1(): | |
################ | |
# solution #1 | |
# | |
# an open file handle will always count as "True", but the file might have | |
# nothing in it. | |
mystery = open('/dev/null', 'r') | |
################ | |
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 challenge_2(): | |
################ | |
# solution #2 | |
# | |
# because floating-point numbers only have about 15 digits of precision, | |
# adding 1 to 1e16 gives no change, and adding 1e16 to 1e33 gives no | |
# change. | |
mystery1 = 1e16 | |
mystery2 = 1e33 | |
################ | |
def sum_some_nums(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_some_nums(mystery1, mystery2) | |
# result: | |
# Program never terminates | |
def challenge_3(): | |
################ | |
# solution #3 | |
# | |
# if the dictionaries reference each other, you'll get this recursion | |
# exception. | |
mystery1 = {} | |
mystery2 = {'foo': mystery1} | |
mystery1['foo'] = mystery2 | |
################ | |
# 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 | |
def challenge_4(): | |
################ | |
# solution #4 | |
# | |
# dictionaries are inherently unordered, and dictionaries with the same | |
# contents can iterate in different orders (and str() iterates over the | |
# elements). here we grow the dictionary first to force it to | |
# re-optimize at a different size, then shrink it back down. | |
size = 100 | |
mystery1 = {i: True for i in range(size)} | |
mystery2 = {'foo': True, 'bar': True} | |
mystery1.update(mystery2) | |
for i in range(size): | |
del mystery1[i] | |
################ | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment