Beispiel #1
0
def e(n):
    "Return the nth convergent of the continued fraction for e."
    if n == 1:
        return 2
    # Collect the first n-1 partial values of e.
    values = deque(take(n-1, partial_values()))
    # Construct the continued fraction, where 'tail' is the recursive component.
    return Fraction(2 + Fraction(1, tail(values)))
Beispiel #2
0
def convergent(D, n):
    """Return the nth convergent of the continued fraction for sqrt(D),
    where D is a non-square positive integer."""
    if n == 1:
        return next(process_cf(D))
    # Collect the first n partial values of D.
    values = deque(take(n, process_cf(D)))
    # Construct the continued fraction, where 'tail' is the recursive component.
    return Fraction(values.popleft() + Fraction(1, tail(values)))
Beispiel #3
0
def p(n):
    if n < 0:
        return 0
    elif n == 0:
        return 1
    else:
        # Generating pentagonals is repeated many times, should think about optimising this.
        pentagonals = list(takewhile(lambda x: x <= n, generalised_pentagonals()))
        terms = [p(n - x) for x in pentagonals]
        coefs = list(take(len(terms), cycle([1, 1, -1, -1])))
        return sum(a*b for (a, b) in zip(terms, coefs))
Beispiel #4
0
def is_lychrel(n):
    start = n + rev(n)
    iterations = iterate(lambda x: x + rev(x), start)
    return not any(is_palindromic(y) for y in take(50, iterations))
Beispiel #5
0
def problem57():
    generate_tails = iterate(tail, 2) # yields 2, tail(2), tail(tail(2)), ...
    expansions = (1 + Fraction(1, t) for t in generate_tails)
    return quantify(take(1000, expansions), pred=check_numerator)