Talk:Weird numbers: Difference between revisions

Content added Content deleted
(→‎A faster and less ambitious algorithm ?: (Showed a variant of hasSum which returns any first sum found))
Line 19: Line 19:
If hasSum considers large divisors first, it can soon exclude all those those too big to sum to a smaller target.
If hasSum considers large divisors first, it can soon exclude all those those too big to sum to a smaller target.
[[User:Hout|Hout]] ([[User talk:Hout|talk]]) 11:52, 24 March 2019 (UTC)
[[User:Hout|Hout]] ([[User talk:Hout|talk]]) 11:52, 24 March 2019 (UTC)

: PS I think we may be able to see and test the operation of '''hasSum''' more clearly if we enrich its type from Bool to [Int] (with a return the empty list for '''False''', and the integers of the first sum found for '''True'''. Let's call this richer-typed variant '''anySum''', and sketch it in Python 3.

::<lang python># anySum :: Int -> [Int] -> [Int]
def anySum(n, xs):
'''First subset of xs found to sum to n.
(Probably more efficient where the xs are sorted in descending
order of magnitude)'''
def go(n, xs):
if xs:
# Assumes Python 3 for list deconstruction
# Otherwise: h, t = xs[0], xs[1:]
h, *t = xs
if n < h:
return go(n, t)
else:
if n == h:
return [h]
else:
ys = go(n - h, t)
return [h] + ys if ys else go(n, t)
else:
return []
return go(n, xs)


print(anySum(7, [1,1,1,1,1,6]))
# -> [1, 6]</lang>