以递归方式删除整数元素

Mal*_*gbo 9 python recursion

我的参数n是一个整数的电话号码.

使用递归我想返回整数中的前三个数字.

我把整数变成了一个单独的数字字符列表,我试图一遍又一遍地删除最后一个数字,直到我离开最后三个,但我仍然坚持如何重复它.

def areaCodes(n):
    n = str(n)  
    n = list(n)
    del n[-1] 
    #n = reduce(opperator.add, n)
    n =  ''.join(n)
    n = int(n)
    return n
Run Code Online (Sandbox Code Playgroud)

我知道我应该以某种方式在回报中重复这个名字,但因为n不是我可以用来重复的整数.我该怎么办?

Mic*_*khi 1

import sys

def areaCodes(n): 
#Create a list 
myList = list(str(n))
#Delete last element
del myList[-1]
#Combine your elements into string list
myListStr =  ''.join(myList)
#Type cast to int
myListInt = int(myListSte)

#Check whether your list satisfies your condition
if len(myList) > 3:
    #Recusivley call the function again
    return areaCodes(myListInt)

#Return your list when recursion completes    
return myListInt


n = 12345
print areaCodes(n)
Run Code Online (Sandbox Code Playgroud)