Given the following array,
l = [
[0, 0, 0, 0, 0],
[0, 2, 1, 1, 0],
[0, 1, 0, 0, 0],
[0, 1, 1, 3, 0],
[0, 0, 0, 0, 0]
]
I am asked to define a recursive function that outputs "yay" every time we find a certain element in this 2D array.
def f(element, lst):
if not lst:
return 0
if len(lst[0])==0:
return f(element,lst[1:])
if lst[0][0]==2:
print("yay")
return f(element,lst[0][1:])
return f(element, lst[0][1:])
f(2, l)
I should be getting "yay" printed once. Instead I get the following:
Traceback (most recent call last):
File "finder.py", line 37, in <module>
f(2, l)
File "finder.py", line 35, in f
return f(element, lst[0][1:])
File "finder.py", line 30, in f
if len(lst[0])==0:
TypeError: object of type 'int' has no len()
Normally you can get the len() of a sublist, but not in the case where you check inside a function.
How can I check for an element in a 2D list using recursion?
if isinstance(lst, list): return 0is needed. Please also note we expect the actual code to be posted, so please correct the declaration.