编写递归函数,使用Python打印第一个N偶数 [英] Write a recursive function to print first N even number using Python
问题描述
我是编程时的绝对初学者world.python是我的第一个编程语言..我解决了它没有递归,但我如何使用递归编码它对我来说变得困难
我尝试了什么:
i尝试了递归,我解决了它
im absolute beginner in programming world.python is my first programming language ..i solved it without recursion but how can i code it using recursion its become difficult for me
What I have tried:
i tried witout recursion and i solved it
推荐答案
您知道,递归函数调用自身直到满足停止条件。因此,在您的情况下,您需要一个功能:
- 检查停止条件(打印出所有数字)并在满足时返回。
- 打印当前号码。
- 使用递增的参数调用自身以打印下一个数字。
You know, a recursive function calls itself until a stop condition is met. so, in your case you need a function that:
- Checks the stop condition (all numbers printed out) and returns if it is met.
- Prints the current number.
- Calls itself with an incremented argument in order to print the next number.
even(n, N)
if n == N then return // stops the recursive process
print(2*n)
even(n+1, N) // recursive call
然后你可以这样称呼
Then you may call it this way
even(0,5)
首先了解递归是什么。你可以通过学习递归来实现。
递归就像一个循环,但它是不同的。
如果你想到经典考试,递归的ples,有阶乘:
First learn what recursion is. You can go that by learning what recursion is.
Recursion is like a loop, but it's different.
If you think about classic exam,ples of recursion, there is factorial:
N! = N * (N - 1)! while N > 1
这显然是递归的,因为因子值的定义用较小值的阶乘表示(直到用完值)
所以在任何语言中实现递归函数的第一个重要步骤是用递归算法来表达操作。即将N偶数表示为递归伪代码。然后你就可以开始实现了它。
试一试:这并不复杂,但是你需要自己解决这个问题 - 得到一个解决方案下次没有教你如何做到这一点!
That's obviously recursive, because the definition of a factorial value is expressed in terms of a factorial of a lesser value (until you run out of values)
So the first big step in implementing a recursive function in any language to to express the operation in terms of a recursive algorithm. I.e. express "N even numbers" as recursive pseudo code. Then you can start implementing it.
Give it a try: this isn't complicated, but it's something you need to get your head around for yourself - being given a solution doesn't teach you anything about how to do it next time!
这篇关于编写递归函数,使用Python打印第一个N偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!