Below is the problem taken from page6 here.
The TAs want to print handouts for their students. However, for some unfathomable reason, both the printers are broken; the first printer only prints multiples of
n1
, and the second printer only prints multiples ofn2
. Help the TAs figure out whether or not it is possible to print an exact number of handouts! First try to solve without a helper function. Also try to solve using a helper function and adding up to the sum.
def has_sum(sum, n1, n2):
"""
>>> has_sum(1, 3, 5)
False
>>> has_sum(5, 3, 5) # 1(5) + 0(3) = 5
True
>>> has_sum(11, 3, 5) # 2(3) + 1(5) = 11
True
"""
Solution
I think there is no mathematical solution except bruteforce recursion.
def f(sum, n1, n2):
"""
>>> f(1, 3, 5)
False
>>> f(5, 3, 5) # 1(5) + 0(3) = 5
True
>>> f(11, 3, 5) # 2(3) + 1(5) = 11
True
>>> f(189, 4, 9)
True
"""
memoiz = []
value = []
def has_sum(sum, n1, n2, x=0, y=0):
if x == 0 and y == 0:
value.append(n1)
value.append(n2) #execute once to reuse tup
if (n1 + n2) == sum:
return True
if (memoiz) and ((n1 + n2) > sum): # inefficient base case, need to improve using math
return False
result1 = False
result2 = False
if (x+1, y) not in memoiz:
memoiz.append((x+1, y)) #memoiz
result1 = has_sum(sum, (x+1)*value[0], y*value[1], x+1, y)
if (x, y+1) not in memoiz:
memoiz.append((x, y+1)) #memoiz
result2 = has_sum(sum, x*value[0], (y+1)*value[1], x, y+1)
return result1 or result2
return has_sum(sum, n1, n2)
Can we improve the base case that returns False
?
in
isO(n)
and I've already shown you how to do it with a decorator. \$\endgroup\$