Two sum: Difference between revisions

Content added Content deleted
(→‎{{header|OCaml}}: explanations)
(→‎{{header|Python}}: Updated primitives and output, pylinted for Python 3, added {Works with})
Line 1,657:
 
or, in terms of '''itertools.product''':
{{Works with|Python|3.7}}
<lang python>'''Finding two integers that sum to a target value.'''
 
<lang python>from itertools import (product)
 
 
# sumTwo :: [Int] -> [Int] -> [(Int, Int)]
def sumTwo(n, xs):
'''All the pairs of integers in xs which
ixs = list(enumerate(xs))
return [ sum to n.
)'''
(fst(x), fst(y)) for (x, y) in (
def go(n):
product(ixs, ixs[1:])
)ixs if= fstlist(x) < fstenumerate(yxs) and n == snd(x) + snd(y)
] return [
(fst(x), fst(y)) for (x, y) in (
product(ixs, ixs[1:])
) if fst(x) < fst(y) and n == snd(x) + snd(y)
print (]
return lambda n: go(n)
 
 
Line 1,675 ⟶ 1,682:
# main :: IO ()
def main():
'''Tests'''
for n in [21, 25]:
 
print (
xs sumTwo(n,= [0, 2, 11, 19, 90, 10])
 
)
print(
fTable(
'The indices of any two integers drawn from ' + repr(xs) +
'\nthat sum to a given value:\n'
)(str)(
lambda x: str(x) + ' = ' + ', '.join(
['(' + str(xs[a]) + ' + ' + str(xs[b]) + ')' for a, b in x]
) if x else '(none)'
)(
sumTwo(xs)
)(enumFromTo(10)(25))
)
 
 
# GENERIC -------------------------------------------------
 
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
 
 
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
 
Line 1,691 ⟶ 1,716:
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
 
 
# DISPLAY -------------------------------------------------
 
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
 
 
# MAIN ---
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre>The indices of any two integers drawn from [0, 2, 11, 19, 90, 10]
<pre>[(1, 3), (2, 5)]
that sum to a given value:
[]</pre>
 
10 -> [(0, 5)] = (0 + 10)
11 -> [(0, 2)] = (0 + 11)
<pre12 -> [(1, 35),] = (2, 5+ 10)]
13 -> [(1, 2)] = (2 + 11)
14 -> (none)
15 -> (none)
16 -> (none)
17 -> (none)
18 -> (none)
19 -> [(0, 3)] = (0 + 19)
20 -> (none)
21 -> [(1, 3), (2, 5)] = (2 + 19), (11 + 10)
22 -> (none)
23 -> (none)
24 -> (none)
25 -> (none)</pre>
 
or, a little more parsimoniously (not generating the entire cartesian product), in terms of '''concatMap''':