简体   繁体   English

Python编写递归函数

[英]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. 我正在尝试编写一个使用Pollard Rho方法查找整数分解因子的python函数。 At this point I am stuck on trying to write a small function that will find f(n) such that: 在这一点上,我坚持尝试编写一个小的函数,该函数将找到f(n)这样: 在此处输入图片说明

where case 0 through 4 behave like: 0至4的情况如下:

在此处输入图片说明

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): 以下是对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: 尝试时,此尝试仅导致错误“ SyntaxError:无法分配给函数调用”:

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? 有人可以帮忙如何编写与案例0到4的行为相匹配的递归函数,如我的代码尝试上面的图像中所述?

You almost had it! 你差点就吃了! Just note that exponentiation is not the operator ^ in python, but ** . 请注意,幂运算不是python中的运算符^ ,而是**

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). 相反,您应该调用函数并将结果分配给局部变量(此处称为answer )。

To write the same function in a simpler way: 要以更简单的方式编写相同的函数:

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

First of all the power operator in python is ** , also you don't need some extra operations like x = xn and f(0) = 2 : 首先,python中的幂运算符是** ,您也不需要一些额外的操作,例如x = xnf(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM