Skip to content

Instantly share code, notes, and snippets.

@pschwede
Last active August 29, 2015 14:20
Show Gist options
  • Save pschwede/2621cb88abb7f903f8d1 to your computer and use it in GitHub Desktop.
Save pschwede/2621cb88abb7f903f8d1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
(c) 2015 pschwede
Solutions to 5 problems every programmer should be
able to solve in less than 1 hour.
"""
# https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour # noqa
from itertools import product
NUMS = [50, 2, 1, 9]
print("Problem 1")
# A for loop
res = 0
for n in NUMS:
res += n
print(res)
# a while loop
res, i = 0, len(NUMS)-1
while i >= 0:
res += NUMS[i]
i -= 1
print(res) # whow.. so un-pythonic
# recursive
mysum = lambda x, ys: mysum(x + ys[0], ys[1:]) if ys else x
print(mysum(0, NUMS)) # functional programming
print("Problem 2")
def myzip(xs, ys):
result = []
for i in range(min(len(xs), len(ys))):
result += [xs[i], ys[i]]
return result
print("myzip([a,b,c],[4,5,6]) =", myzip(['a', 'b', 'c'], [4, 5, 6]))
print("Problem 3")
fibs = [0, 1]
while len(fibs) < 100:
fibs.append(sum(fibs[-2:]))
print(fibs)
print("Problem 4")
print(int("".join([s for s in sorted([str(n) for n in NUMS], reverse=True)])))
print("Problem 5")
FUNCS, RANGE, TARGET = [' + ', ' - ', ''], range(1, 10), 100
for combi in product(FUNCS, repeat=len(RANGE)-1):
equation = ""
for n, f in zip(RANGE, combi):
equation += "%i%s" % (n, f)
equation += "%i" % RANGE[-1]
if eval(equation) == TARGET: # noqa
print(equation, "=", TARGET)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment