0
\$\begingroup\$

I've written this code to calculate the Sylvester sequence, which is defined as $$s_n = s_{n-1}(s_{n-1}-1)+1$$ where \$s_0=2\$.

def sylvester_term(n): """ Returns the maximum number of we will consider in a wps of dimension n >>> sylvester_term(2) 7 >>> sylvester_term(3) 43 """ if n == 0: s_n = 2 return s_n s_n = sylvester_term(n-1)*(sylvester_term(n-1)-1)+1 return s_n print(s_n) print(sylvester_term(3)) 
\$\endgroup\$
0

    1 Answer 1

    5
    \$\begingroup\$

    The print() call at the end of the function is unreachable and should be removed.

    There's no need to assign s_n before returning.

    PEP 8, the official Python style guide, recommends a space before and after every binary operator.

    def sylvester_term(n): """docstring here""" if n == 0: return 2 else: return sylvester_term(n - 1) * (sylvester_term(n - 1) - 1) + 1 

    Next, you should notice that sylvester_term(n - 1) is used twice in the expression. You should definitely assign that result to a variable, otherwise your function will require drastically more time — O(2n) instead of O(n).

    def sylvester_term(n): """Return the maximum number of we will consider in a wps of dimension n >>> sylvester_term(2) 7 >>> sylvester_term(3) 43 """ if n == 0: return 2 else: prev_sylvester_term = sylvester_term(n - 1) return prev_sylvester_term * (prev_sylvester_term - 1) + 1 
    \$\endgroup\$

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.