Complexity question on Python 3 lists

Franck Ditter franck at ditter.org
Wed Feb 15 19:20:21 CET 2012


What is the cost of calling primes(n) below ? I'm mainly interested in
knowing if the call to append is O(1), even amortized.
Do lists in Python 3 behave like ArrayList in Java (if the capacity
is full, then the array grows by more than 1 element) ?

def sdiv(n) :     # n >= 2
    """returns the smallest (prime) divisor of n"""
    if n % 2 == 0 : return 2
    for d in range(3,int(sqrt(n))+1,2) :
        if n % d == 0 : return d
    return n

def isPrime(n) :
    """Returns True iff n is prime"""
    return n >= 2 and n == sdiv(n)

def primes(n) :           # n >= 2
    """Returns the list of primes in [2,n]"""
    res = []
    for k in range(2,n+1) :
        if isPrime(k) : res.append(k)    # cost O(1) ?
    return res

Thanks,

    franck



More information about the Python-list mailing list