暂无分类
暂无标签
发布于2020-05-15 17:07 阅读(932) 评论(0) 点赞(10) 收藏(4)
0
1
2
3
4
5
6
7
带你用练习来熟悉递归的用法
递归最最最重要的两个point:
1. 找到递归结束的条件,如果没有结束的条件,就会陷入无限循环
2. 找到不断缩小参数范围的等价式
从这两个point去思考题目,再补充剩下的代码,就会轻松许多啦
我们来看些练习,题目的要求我会以input和output的形式注释在代码中
Example1:
def rec_sum(lst):
"""
input: 由整数组成的list
output: 求这些整数的和
"""
For example:
<<<rec_sum([1,2,3,4])
10 (1+2+3+4)
""" 第一个if就是递归的结束条件"""
if len(lst) == 0:
return 0
else:
return lst[0] + rec_sum(lst[1:])
"""缩小范围:rec_sum(lst[1:])"""
print(rec_sum([1,2,3,4]))
Example2:
def rec_factorial(n):
"""
input:输入一个整数n
output:输出整数的阶乘,n!
"""
For example:
<<<input: rec_factorial(3)
6 ( 3! = 3 * 2 * 1)
if n == 0:
res = 1
else:
res = n * rec_factorial(n-1)
return res
print(rec_factorial(3))
Example3:
def dup_rem(s):
"""
input:输入一个string
output:输出无连续重复元素的string
"""
For example:
<<<dup_rem('fffsggfd')
‘fsgfd’
if len(s) <= 1:
return s
if s[0] == s[1]:
return dup_rem(s[1:])
if s[0] != s[1]:
return s[0] + dup_rem(s[1:])
print(dup_rem('fffsggfd'))
Example4:
def gcd(a, b):
"""
Input : two integers a and b such that not a==b==0
Output: greatest common divisor of a and b
"""
For example:
>>> gcd(18, 27)
9
"""
if a % b == 0:
return b
else:
return gcd(b, a % b)
原文链接:https://blog.csdn.net/Huangkaihong/article/details/106130208
0
1
2
3
4
5
6
7
8
作者:9384vfnv
链接: https://www.pythonheidong.com/blog/article/371914/94dee245c8a0f6856e89/
来源: python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系z452as@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!