Two sum: Difference between revisions
→{{header|Python}}: Added a version expressing twoSum in terms of product
(→{{header|Python}}: Added a version expressing twoSum in terms of product) |
|||
Line 1,577:
=={{header|Python}}==
{{trans|Perl 6}}
<lang python>def two_sum(arr, num):
def two_sum(arr, num):▼
i = 0
j = len(arr) - 1
Line 1,593 ⟶ 1,592:
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))</lang>
or, in terms of itertools.product:
</lang>▼
<lang python>from itertools import (product)
# sumTwo :: Int -> [Int] -> [(Int, Int)]
ixs = list(enumerate(xs))
return [
(fst(x), fst(y)) for (x, y) in (
product(ixs, ixs[1:])
) if fst(x) < fst(y) and n == snd(x) + snd(y)
]
# TEST ----------------------------------------------------
# main :: IO ()
def main():
for n in [21, 25]:
print (
sumTwo(n, [0, 2, 11, 19, 90, 10])
)
# GENERIC -------------------------------------------------
# fst :: (a, b) -> a
def fst(tpl):
return tpl[0]
# snd :: (a, b) -> b
def snd(tpl):
return tpl[1]
if __name__ == '__main__':
▲ main()</lang>
{{Out}}
<pre>[(1, 3), (2, 5)]
[]</pre>
=={{header|Racket}}==
|