0

Assume you have the following compute function, using python built-in sum function:

def compute(a_list):
    for i in range(0, n):                        #Line 1
        number = sum(a_list[0:i + 1])/(i+1)      #Line 2
    return number

What would the time-complexity for something like this look like?

Line 1 is executed n number of times, but Line 2, having the built-in sum function (O(n)), would it execute n^2 number of times? Therefore the algorithm would be O(n^2).

For each iteration of i, Line 2 is executed 1 + 2 + 3 + ... + n-2 + n-1 + n. The sum of these terms is

enter image description here

Is this correct?

2
  • It is correct. It's O(n^2) Commented Feb 20, 2019 at 8:24
  • 2
    where does n come from? I'd guess either n = len(a_list) or def compute(a_list, n) Commented Feb 20, 2019 at 8:37

1 Answer 1

1

I'd say that line 1 is executed once, and this causes line 2 to be executed n times. the list subscript is O(n), and the sum is also O(n). division, addition and assignment are all O(1).

compute is therefore O(N^2) as the largest terms are evaluating an O(n) operation O(n) times.

note that, as written, it discards all intermediate results, so it could be rewritten as:

def compute(a_list):
    return sum(a_list[0:n])/n

which would be O(n).

Sign up to request clarification or add additional context in comments.

2 Comments

your "rewritten" part uses n => NameError
@PatrickArtner yup, OP also has this… they didn't say where n is coming from!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.