Complexity of splits

Jean-Guillaume Pyraksos jeapy at free.fr
Mon May 12 09:57:02 EDT 2003


As I am digging into my Python studies, I started translating some 
elementary Lisp recursive algorithms...

def length(L):
   if not(L): 
      return 0
   return 1 + length(L[1:len(L)])

is (?) the Pythonization of the Lisp function:

(defun length (L)
  (if (not L)
      0
      (+ 1 (length (cdr L)))))

If n is the length of L, then the Lisp algorithm is O(n) but the Python 
algorithm is O(n^2) as L([1:len(L)]) builds a n-1 elements list. Am i 
wrong ? I chose a split as it seems that taking the cdr of a list is not 
a primitive operation in Python, did I miss it ? Probably. What's the 
name of that operation  so that the recursive algorithm stays O(n) ? I 
don't want (for now) to translate it into a loop.
Thanks,

    [jgp]




More information about the Python-list mailing list