Padovan n-step number sequences: Difference between revisions
→Python: Functional: Updated formatting – foregrounded parallels with with N-Step Fibonacci task.
SqrtNegInf (talk | contribs) (Added Perl) |
(→Python: Functional: Updated formatting – foregrounded parallels with with N-Step Fibonacci task.) |
||
Line 1,062:
Patterns of functional composition are constrained more by mathematical necessity than by arbitrary convention, but this still leaves room for alternative idioms of functional coding in Python. It is to be hoped that others will contribute divergent examples, enriching the opportunities for contrastive insight which Rosetta code aims to provide.
<lang python>'''Padovan
from itertools import chain, islice, repeat
#
def
'''Non-finite series of N-step
defined by a recurrence relation.
'''
def
return
return unfoldr
relation
)(
take(1 + n)(
repeat(1) if 3 > n else
)
)
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First 15 terms each n-step
where n is drawn from [2..8]
'''
table = list(
map(
in take(15)(nStepPadovan(n))
)
)
),
(str(x) for x in xs),
xs
)
)
print('Padovan n-step series:\n')
print(
spacedTable(table)
)
# ----------------------- GENERIC ------------------------
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
def go(xs):
return (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
return go
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
Line 1,122 ⟶ 1,144:
valueResidue = f(valueResidue[1])
return go
# ---------------------- FORMATTING ----------------------
#
def spacedTable(rows):
columnWidths = list(map(
lambda col: max([len(x) for x in col]),
zip(*rows)
row,
)
for row in
])
# MAIN ---
if __name__ == '__main__':
Line 1,172 ⟶ 1,170:
{{Out}}
<pre>Padovan n-step series:
8 -> 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362</pre>
=={{header|Raku}}==
|