|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
023,024讲课后作业01递归解决append insert出来列表顺序一样?
写一个函数get_digits(n),将参数n分解出每个位的数字并按顺序存放到列表中。举例:get_digits(12345) ==> [1, 2, 3, 4, 5]
写的递归版本
- >>> def fun1(n):
- lenght=len(str(n))
- def fun2(lenght):
- str1=''
- list1=[]
- if lenght==0:
- return list1
- else:
- str1=str(n//10**(lenght-1))
- list1.insert(0,(str1[-1]))
- return fun2(lenght-1)+list1
- return fun2(lenght)
- >>> fun1(123456)
- ['6', '5', '4', '3', '2', '1']
复制代码
这是加到列表第一个位置
- >>> def fun1(n):
- lenght=len(str(n))
- def fun2(lenght):
- str1=''
- list1=[]
- if lenght==0:
- return list1
- else:
- str1=str(n//10**(lenght-1))
- list1.append(str1[-1])
- return fun2(lenght-1)+list1
- return fun2(lenght)
- >>> fun1(123456)
- ['6', '5', '4', '3', '2', '1']
复制代码
这是append,加到列表最后一个位置,出来结果一样。
这是为什么,有什么办法在函数内把列表翻转过来输出?
- def fun1(n):
- lenght=len(str(n))
- temp_str1=''
- list1=[]
- for i in range(1,lenght+1):
- temp_str1=str(n//(10**(i-1)))
- list1.insert(0,(temp_str1[-1]))
- return list1
复制代码
这是迭代的办法用insert就可以正常输出
把你代码的else 代码块下的 return fun2(lenght-1)+list1 位置对调下即可
但是注意 小甲鱼要返回的是 列表里面是整数的,而你把他变成了字符串,在你代码的 str1[-1] 那转为 int 就可
- def fun1(n):
- lenght = len(str(n))
- def fun2(lenght):
- list1 = []
- if lenght == 0:
- return list1
- else:
- str1 = str(n // 10 ** (lenght - 1))
- list1.insert(0,int((str1[-1])))
- return list1+fun2(lenght - 1)
- return fun2(lenght)
- print(fun1(123456))
复制代码
但是其实不用内嵌函数,直接一个函数就够了:
- list1 = []
- def fun1(n):
- if n > 0:
- list1.insert(0,n%10)
- return fun1(n//10)
- fun1(123456)
- print(list1)
复制代码
直接在原列表上进行添加元素
|
|