Equilibrium index: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: Tidied the Prelude functions version)
Line 2,101: Line 2,101:
equals the sum of values to the right.'''
equals the sum of values to the right.'''
def go(xs):
def go(xs):
'''Left scan from accumulate, right scan derived from left'''
'''Left scan from accumulate,
right scan derived from left
'''
ls = list(accumulate(xs))
ls = list(accumulate(xs))
n = ls[-1]
n = ls[-1]
return [i for (i, (x, y)) in enumerate(zip(
return [
ls,
i for (i, (x, y)) in enumerate(zip(
[n] + [n - x for x in ls[0:-1]]
ls,
)) if x == y]
[n] + [n - x for x in ls[0:-1]]
)) if x == y
]
return go(xs) if xs else []
return go(xs) if xs else []




# TEST -------------------------------------------------
# ------------------------- TEST -------------------------
# main :: IO ()
# main :: IO ()
def main():
def main():
Line 2,129: Line 2,133:




# GENERIC -------------------------------------------------
# ----------------------- GENERIC ------------------------



# tabulated :: String -> (a -> b) -> [a] -> String
# tabulated :: String -> (a -> b) -> [a] -> String
def tabulated(s):
def tabulated(s):
'''heading -> function -> input List -> tabulated output string'''
'''heading -> function -> input List
-> tabulated output string
def go(f, xs):
'''
def go(f):
def width(x):
def width(x):
return len(str(x))
return len(str(x))
w = width(max(xs, key=width))
def cols(xs):
return s + '\n' + '\n'.join([
w = width(max(xs, key=width))
str(x).rjust(w, ' ') + ' -> ' + str(f(x)) for x in xs
return s + '\n' + '\n'.join([
str(x).rjust(w, ' ') + ' -> ' + str(f(x))
])
return lambda f: lambda xs: go(f, xs)
for x in xs
])
return cols
return go