Pascal's triangle: Difference between revisions
→Functional Python: pylinted for Python 3, tidied.
(→Functional Python: pylinted for Python 3, tidied.) |
|||
Line 4,113:
The itertools module yields a simple functional definition of '''scanl''' in terms of '''accumulate''' and '''chain''', and a similar definition of '''zipWith''' in terms of '''starmap'''.
With a scanl and a zipWith to hand, we can derive both finite and non-finite lists of pascal rows from a single '''
{{Works with|Python|3.7}}
<lang python>from itertools import (accumulate, chain, islice, starmap)▼
<lang python>'''Pascal's triangle'''
from operator import (add)
#
def
'''A row of Pascal's triangle
derived from the previous row.'''
return zipWith(add)([0] + xs)(xs + [0])
#
def
'''A non-finite stream of
return iterate(pascal)(▼
Pascal's
)▼
#
def
'''The first n rows of Pascal's triangle.'''
return scanl(lambda a, _: pascal(a))(▼
def go(a,
return nextPascal(a)
range(1, n)▼
▲ )
# TESTS ---------------------------------------------------
# main :: IO ()
def main():
'''Test of two different approaches:
print (▼
- taking from a non-finite stream of rows
- constructing a finite
take(7)(pascalTriangle()), # Non finite,
)▼
finitePascalRows(7) # finite.
▲ )))
▲ )
)▼
# showPascal :: [[Int]] -> String
def showPascal(xs):
'''Stringification of a list of
Pascal triangle rows.'''
ys = list(xs)
Line 4,169 ⟶ 4,176:
# GENERIC -------------------------------------------------
# center :: Int -> Char -> String -> String
def center(n):
'''String s padded with c to approximate centre,
fitting in but not truncated to width n.
def go(c, s):
qr = divmod(n - len(s), 2)
Line 4,179 ⟶ 4,190:
#
def iterate(f):
'''An infinite list of repeated applications of f to x.'''
def go(x):
v = x
while True:
yield
v = f(v)
return lambda x: go(x)
# scanl is like reduce, but returns a succession of▼
# intermediate values, building from the left.▼
# scanl :: (b -> a -> b) -> b -> [a] -> [b]
def scanl(f):
return lambda a: lambda xs: (
accumulate(chain([a], xs), f)
Line 4,207 ⟶ 4,213:
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.'''
return lambda xs: (
xs[0:n]
Line 4,212 ⟶ 4,220:
else list(islice(xs, n))
)
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
'''A list constructed by zipping with a
custom function, rather than with the
default tuple constructor.'''
return lambda xs: lambda ys: (
list(
)
# MAIN ---
if __name__ == '__main__':
main()</lang>
|