[Tutor] Question on lists

Joseph J. Strout joe@strout.net
Thu, 18 Mar 1999 08:41:48 -0800


The basic problem is that you're saying:

>             a.insert(len(a), i)
>             factor(n/i)    # Factor quotient

i.e., you're saying "now factor the quotient", but you're not doing
anything with the result of this factorization!  You're imagining that it
will get appended to a, but how would Python know to do that unless you
tell it?

Also, I'd recommend using a.append to append an element to a, rather than
the insert construction used above.

Finally, there's a minor bug where you're factor() does not return a prime
number as its own factor, as it should.  The corrected function looks like
this:

# Factor by trial division:
def factor(n):
     a = []                # Is there a better way to define a?
     k = floor(sqrt(n))
     for i in range(2, k+1):
          if n%i == 0:
             a.append(i)   ### (append rather than insert)
             a.extend(factor(n/i))    ### add the factors of the quotient
             return a      ### don't break; just return
     # if not divisible by any of the above, then it must be prime
     return [n]


Cheers,
-- Joe
,------------------------------------------------------------------.
|    Joseph J. Strout           Biocomputing -- The Salk Institute |
|    joe@strout.net             http://www.strout.net              |
`------------------------------------------------------------------'