1

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?

MDS0LDI3R
  • 37
  • 5

2 Answers2

3

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
wim
  • 338,267
  • 99
  • 616
  • 750
  • thank you! I think on this attempt at writing this portion of code I stuck too closely to the vague blueprint in my reading and let my uncertainty in writing a recursive function in a programming setting distract me. And thank you for the reduced clutter method you suggest. – MDS0LDI3R Oct 31 '15 at 19:58
3

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
Mazdak
  • 105,000
  • 18
  • 159
  • 188