|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
写一个函数get_digits(n),将参数n分解出每个位的数字并按顺序存放到列表中。举例:get_digits(12345) ==> [1, 2, 3, 4, 5]
代码如下:
- list1 = []
- def get_digits(n):
- lenth = len(str(n))
- nums = 10**(lenth)
- if n >= 10:
- a = n // nums
- b = n % nums
- list1.append(a)
- return get_digits(b)
- else:
- list1.append(n)
- return list1
复制代码
每次运行结果总是
- >>> get_digits(123)
- Traceback (most recent call last):
- File "<pyshell#6>", line 1, in <module>
- get_digits(123)
- File "D:\下载\python\学习\函数6.py", line 53, in get_digits
- return get_digits(n)
- File "D:\下载\python\学习\函数6.py", line 53, in get_digits
- return get_digits(n)
- File "D:\下载\python\学习\函数6.py", line 53, in get_digits
- return get_digits(n)
- [Previous line repeated 1020 more times]
- File "D:\下载\python\学习\函数6.py", line 46, in get_digits
- lenth = len(str(n))
- RecursionError: maximum recursion depth exceeded while getting the str of an object
复制代码
是返回值有问题吗?但是我也没看出来啊
核心思路就是用地板除法获取每一位的值,再放到列表里
哪位大神帮看看是哪里出了问题
本帖最后由 qiuyouzhi 于 2021-2-27 16:06 编辑
你那地板除除的也不对鸭..
而且你递归传入的参数也不对,应该传a
- list1 = []
- def get_digits(n):
- while n:
- b = n % 10
- a = n // 10
- list1.insert(0, b)
- return get_digits(a)
- return list1
- print(get_digits(123))
- print(list1)
复制代码
|
|