Brain going crazy with recursive functions

James Stroud jstroud at mbi.ucla.edu
Sun Dec 7 03:47:13 EST 2008


James Stroud wrote:
> def linear_search(array, truth_func, loc=(0,0)):
>   idx1, idx2 = loc
>   if idx1 >= len(array):
>     return None
>   if idx2 >= len(array[idx1]):
>     return linear_search(array, truth_func, (idx1+1, 0))
>   value = array[idx1][idx2]
>   tf = truth_func(value)
>   if tf:
>     return loc
>   else:
>     return linear_search(array, truth_func, (idx1, idx2+1))
> 
> a = [[5, 3, 4], [2, 0, 1], [8, 6, 7]]
> linear_search(a, lambda x: x==0)

PS: If I just made it to easy for you, you can practice by generalizing 
this to an N-dimensional array using recursion. I'm tempted to do it 
myself but I'm going to try to resist instead and do some work that pays.



More information about the Python-list mailing list