Greatest subsequential sum: Difference between revisions
→Functional Python: pylinted for Python 3, added {Works with} tag
(→{{header|Haskell}}: foldl -> foldr (usually preferable anyway, and here allows an efficient (:) in lieu of a (++)) |
(→Functional Python: pylinted for Python 3, added {Works with} tag) |
||
Line 2,741:
===Functional===
{{Trans|Haskell}}▼
We can efficiently derive sum and sequence together, without mutation, using '''reduce''' to express a linear accumulation over a fold:
▲{{Trans|Haskell}}
<lang python>from functools import (reduce)▼
{{Works with|Python|3.7}}
<lang python>'''Greatest subsequential sum'''
# maxSubseq :: [Int] -> [Int] -> (Int, [Int])
def maxSubseq(xs):
'''Subsequence of xs with the maximum sum'''
def go(ab, x):
(m1, m2) = ab[0]
return (
return reduce(go, xs, ((0, []), (0, [])))[1]
# TEST -----------------------------------------------------------
print(
maxSubseq(
|