|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 INFINI 于 2016-11-29 00:52 编辑
递归实在太搞脑子了,请大神帮忙理理思路
01.
- def huiwen(x):
- if len(x) <= 1:
- return True
- elif x[0] == x[-1]:
- return huiwen(x[1:-1])
- else:
- return False
- txt = input('请输入一句话:')
- if huiwen(txt):
- print('您输入的这句话符合回文格式。')
- else:
- print('您输入的这句话不符合回文格式。')
复制代码
为什么return huiwen(x[1:-1]) 前这个return必须要呢?有点不好理解。
02.- def Dec2Bin(dec):
- result = ''
-
- if dec:
- result = Dec2Bin(dec//2)
- return result + str(dec%2)
- else:
- return result
- print(Dec2Bin(62))
复制代码
- def bin_new(x, result=''):
- return '0b' + result[::-1] if not x else bin_new(x // 2, result + str(x % 2))
复制代码
小甲鱼和我的基本差不多啊,为啥我的必须要反转一下呢?
1、python 函数返回值 return,函数中一定要有return返回值才是完整的函数。如果你没有python 定义函数返回值,那么会得到一个结果是None对象,而None表示没有任何值。
2.LZ的result其实一直处于空的状态,根本没有用上,所以每次都是str(x%2)在前,而小甲鱼老师的是str(x%2)每次都是在后,所以你的需要翻转
|
|