[Tutor] recursivity and lists

Danny Yoo danny.yoo at gmail.com
Fri Mar 4 16:33:58 EST 2016


> As we can see, we have to do a lot more consideration of what state
> our values are in, due to all the mutation happening.  It also shows
> that the second recursive call to the linear_merge() is not really
> using it to merge: it's really trying to select the list that was used
> to accumulate results.  We'd get the same results with:
>
> ######################################
> def linear_merge1(list1, list2):
>   if list1==[]: return list2
>   elif list2==[]: return list1
>   elif list1[-1]>list2[-1]:
>     a=list1.pop()
>     linear_merge(list1,list2).append(a)
>     return list1 or list2
>   else:
>     a=list2.pop()
>     linear_merge(list1,list2).append(a)
>     return list1 or list2
> ######################################


Sorry: I made a mistake when typing out the internal recursive calls.
Substitute 'linear_merge1' in places where it had 'linear_merge'.

#####################################
def linear_merge1(list1, list2):
  if list1==[]: return list2
  elif list2==[]: return list1
  elif list1[-1]>list2[-1]:
    a=list1.pop()
    linear_merge1(list1,list2).append(a)
    return list1 or list2
  else:
    a=list2.pop()
    linear_merge1(list1,list2).append(a)
    return list1 or list2
######################################



> So, yeah, the code is *much* too clever for it's own good.  :P

Substitute "it's" with "its".


More information about the Tutor mailing list