Sylvester's sequence: Difference between revisions
Content added Content deleted
JsfasdF256 (talk | contribs) No edit summary |
|||
Line 900: | Line 900: | ||
reduce(lambda a, x: a + 1 / x, xs, 0) |
reduce(lambda a, x: a + 1 / x, xs, 0) |
||
) |
) |
||
# MAIN --- |
|||
if __name__ == '__main__': |
|||
main()</lang> |
|||
{{Out}} |
|||
<pre>First 10 terms of OEIS A000058: |
|||
2 |
|||
3 |
|||
7 |
|||
43 |
|||
1807 |
|||
3263443 |
|||
10650056950807 |
|||
113423713055421844361000443 |
|||
12864938683278671740537145998360961546653259485195807 |
|||
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443 |
|||
Sum of the reciprocals of the first 10 terms: |
|||
0.9999999999999999</pre> |
|||
Or as an iteration: |
|||
<lang python>'''Sylvester's sequence''' |
|||
from functools import reduce |
|||
from itertools import islice |
|||
# sylvester :: [Int] |
|||
def sylvester(): |
|||
'''A non finite sequence of the terms of OEIS A000058 |
|||
''' |
|||
return iterate( |
|||
lambda x: x * (x - 1) + 1 |
|||
)(2) |
|||
# ------------------------- TEST ------------------------- |
|||
# main :: IO () |
|||
def main(): |
|||
'''First terms, and sum of reciprocals.''' |
|||
print("First 10 terms of OEIS A000058:") |
|||
xs = list(islice(sylvester(), 10)) |
|||
print('\n'.join([ |
|||
str(x) for x in xs |
|||
])) |
|||
print("\nSum of the reciprocals of the first 10 terms:") |
|||
print( |
|||
reduce(lambda a, x: a + 1 / x, xs, 0) |
|||
) |
|||
# ----------------------- GENERIC ------------------------ |
|||
# iterate :: (a -> a) -> a -> Gen [a] |
|||
def iterate(f): |
|||
'''An infinite list of repeated |
|||
applications of f to x. |
|||
''' |
|||
def go(x): |
|||
v = x |
|||
while True: |
|||
yield v |
|||
v = f(v) |
|||
return go |
|||