Skip to content

Instantly share code, notes, and snippets.

@johnpena
Created May 8, 2015 17:09
Show Gist options
  • Save johnpena/2b3b4f90bbca0253f604 to your computer and use it in GitHub Desktop.
Save johnpena/2b3b4f90bbca0253f604 to your computer and use it in GitHub Desktop.
Solutions to this blog post
"""https://blog.svpino.com/2015/05/08/solution-to-problem-5-and-some-other-thoughts-about-this-type-of-questions"""
from itertools import permutations, product
def problem1():
def forloop(numbers):
s = 0
for number in numbers:
s += number
return s
def whileloop(numbers):
s = 0
current_index = 0
while current_index < len(numbers):
s += numbers[current_index]
current_index += 1
return s
def recursion(numbers):
if len(numbers) == 0:
return 0
return numbers[0] + recursion(numbers[1:])
l = [1, 2, 3, 4]
expected_sum = sum(l)
forloop_sum = forloop(l)
whileloop_sum = whileloop(l)
recursion_sum = recursion(l)
print "problem 1:"
print "forloop sum: {}".format(forloop_sum)
assert forloop_sum == expected_sum
print "whileloop sum: {}".format(whileloop_sum)
assert whileloop(l) == expected_sum
print "recursion sum: {}".format(recursion_sum)
assert recursion(l) == expected_sum
def problem2():
expected = ['a', 1, 'b', 2, 'c', 3]
l1 = ['a', 'b', 'c']
l2 = [1, 2, 3]
flatten = lambda l: [i for sublist in l for i in sublist]
combined = flatten(zip(l1, l2))
print "problem 2:"
print "solution is {}".format(combined)
assert combined == expected
def problem3():
def fibo(n):
fibz = [0, 1]
while len(fibz) < 100:
fibz.append(fibz[-1] + fibz[-2])
return fibz
fib100 = fibo(100)
print "problem 3:"
print "solution is {}".format(fib100)
assert len(fib100) == 100
def problem4():
all_permutations = lambda l: [p for p in permutations(l)]
concat_to_int = lambda l: int("".join([str(i) for i in l]))
test_input = [50, 2, 1, 9]
solution = max([concat_to_int(i) for i in all_permutations(test_input)])
print "problem 4:"
print "solution is {}".format(solution)
assert solution == 95021
def problem5():
# really slow utility funcs
flatten = lambda l: [i for sublist in l for i in sublist]
stringify = lambda t: "".join(flatten([str(i) for i in flatten(t)])).replace(" ", "")
only_sum_100 = lambda l: [i for i in l if eval(i) == 100]
nums = range(1, 9)
chars = ["+", "-", " "]
steps = [[x for x in product([str(j)], chars)] for j in nums]
all_combos = [i for i in product(*[step for step in steps])]
all_possibilities = [stringify(combo) + "9" for combo in all_combos]
all_equaling_100 = only_sum_100(all_possibilities)
print "problem 5:"
print "solutions are {}".format(all_equaling_100)
print all_equaling_100
assert len(all_equaling_100) == 11
if __name__ == "__main__":
problem1()
problem2()
problem3()
problem4()
problem5()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment