MDS0LDI3R
MDS0LDI3R

Reputation: 37

Python writing recursive function

This question has to do with how to write a recursive function that fits a sequence not printing stars in the form of triangles.

I am trying to write a python function that uses the Pollard Rho method of finding the factorization of an integer. At this point I am stuck on trying to write a small function that will find f(n) such that: enter image description here

where case 0 through 4 behave like:

enter image description here

I guess I am really confused about how to go about setting up the base case and getting the function to call on itself to calculate the requested iteration of the recursive function. Below is an attempt that doesn't even work for f(0):

def f(xn):
    if xn == 0:
        answer = 2
        return answer
    else:
        x = xn
        f(0) = 2
        f(xn) = f(x - 1)^2 + 1
        return f(xn)

This attempt simply resulted in an error "SyntaxError: can't assign to function call" when I tried:

print f(0)

Can anyone please help on how to write such a recursive function that matches the behavior of case 0 through 4 as described in the image above my code attempt?

Upvotes: 1

Views: 462

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

First of all the power operator in python is **, also you don't need some extra operations like x = xn and f(0) = 2 :

>>> def my_func(n):
...     if n == 0 :
...        return 2
...     return my_func(n-1)**2 +1
... 
>>> my_func(1)
5
>>> my_func(2)
26
>>> my_func(3)
677

Upvotes: 3

wim
wim

Reputation: 363566

You almost had it! Just note that exponentiation is not the operator ^ in python, but **.

def f(xn):
    if xn == 0:
        answer = 2
        return answer
    else:
        answer = f(xn - 1)**2 + 1
        return answer

Assigning to a function call was a syntax error in your code. Instead, you should call the function and assign the result to a local variable (that is called answer, here).

To write the same function in a simpler way:

def f(xn):
    return (1 + f(xn-1)**2) if xn else 2

Upvotes: 3

Related Questions