I'm writing three functions which iterate over lists, I want do this recursively, but I think this code is not as efficient as it could be.
def flatten(lst):
if type(lst)==int:
return [lst]
elif lst==[]:
return lst
else:
return sum([flatten(sub) for sub in lst], [])
def size(lst): #counts how many numbers and pairs of parentheses in the list
global cnt
cnt=0
if type(lst)==int:
cnt+=1
return 1
if lst==[]:
cnt+=1
return 1
else:
return (sum([size(sub) for sub in lst])+cnt)
def transform(f, lst):
if lst==[]:
return []
if isinstance(lst,(int,float)):
return f(lst)
else:
return [transform(f,sub) for sub in lst]