I am 4 weeks into programming with python and now we are talking about recursion.
Problem statement
I need to write a function with one parameter which is a list; the function must check if the list and its sublists satisfy the criteria:
- all elements in the list are ints;
OR
- all elements in the list are lists,
- AND all sublists also satisfy the criteria.
For example:
[1, 2] True
[[1, 2, [1]]] False
[[1], [2], [[3], [1]]] True
And so on.
My attempt so far
I tried to check the width first and then go into the depth. Go level per level deeper. But this wont work because at some point this
[[1], [2], [[3], [1]]]
goes to
1, 2, [3], [1]
which is wrong.
I realised i need to go into the depth first and if I can't go deeper and checked everything I need to go back. Something like a binary tree. And there is my problem. I don't know when I am deep and finished to come back to my "leftover" list.
def intSuperListe(list_to_check):
for idx, item in enumerate(list_to_check):
if idx + 1 < len(list_to_check):
if type(list_to_check[idx]) == type(list_to_check[idx + 1]):
if type(list_to_check[idx]) == int:
if len(list_to_check) == 1 or len(list_to_check) == 2:
return True
else:
continue
elif type(list_to_check[idx]) == list:
intSuperListe(list_to_check[idx])
return True
return False
elif type(list_to_check[idx]) == int:
return True
elif type(list_to_check[idx]) == list:
intSuperListe(list_to_check[idx])
break
else:
return False
This was my try.
Any help is extremely appreciated.