问题描述
I did a little test to see how could it work.我正在使用IDLE Python,所以我基本上必须编写一个函数,该函数需要一个整数并返回具有以下形式的元组:
检测0到4之间的位数,并检测5到9之间的位数。是否可以递归进行?我尝试了所有我能想到的,但始终出错。谢谢。
解决方法
是的。
def cnt(n,res = (0,0)):
if n == 0:
return res
q = n % 10
if q <= 4:
res = tuple([res[0] + 1,res[1]])
else:
res = tuple([res[0],res[1] + 1])
return cnt(n//10,res)
print(cnt(12456319))
输出:(5,3)