foo = []
i = 1
while i < n:
foo= foo + ["a"]
i*=2
What is the time complexity of this code?
My thoguht is:
the while loop does log(n) iteration. For each iteration new list is created.
So, the total time complexity is: O(log^2(n)).
Am I right?
The loop does log(n) iterations.
Now, assuming
foo = foo + ["a"]
copies immediately each element infoo
to do the concatenation (as opposed to some fancy list-appending) then for each iteration there are also at mostlog(n)
copies.So yes, it is
log(n)*log(n)
=log^2(n)
Let’s assume the loop iterates n instead of log(n) times, then the array copy takes 0+1+2+3+4+…+n-2 operations; and with n+2 it takes
operations. For simplicity, let’s replace n+2 by m, so n+2 = m, thus n = m-2, and
which we will use later as
Now as the loop’s limit is not n+2 but log(n), there are not
but
operations, which is
The
while
loop iterates log(n) times.foo + ["a"]
: Create a new list by copying the original list. According to Time Complexity - Python Wiki, copying a list take O(n).Time complexity => 1 + 2 + 3 + ... + log(n) => (log(n) + 1) * log(n) / 2 => O(log2n)
I ran a
timeit
: (CPython 2.7.5 64bit, Windows 7)Result: