educative.io

Educative

Example 1: Measuring Time Complexity range(n) and sum+=1

Hi all!

I was going through and trying to understand the range(n) number of executions and why is it n? I assumed that the range(n) would have been called once when we start the loop and then that is it. Also I saw that sum+=1 number of executions is 2. Is that not 3? variable access, variable assignment, addition

1 Like

I am also wondering about this:

Also I saw that sum+=1 number of executions is 2. Is that not 3? variable access, variable assignment, addition
In one article this is explained as 3 and then in another it is shown as 2.

@Educative_CS

1 Like

Hi @Hassan and @constantin_mitides!

Thanks for reaching out!

So while yes, range(n) is only executed once, it’s execution cost is n. Also, you are right about sum+=1. We’ve made a few changes to the lessons to reflect these excellent points.

We hope Educative has inspired to further your learning, and please drop us a note if you have any other questions or concerns.

Best Regards,
Team Educative

Ah gotcha thank you for the reply!

My understanding is that range() is a generator (Python 3 +), and that every time it is reached to return another integer, the cost is one operation.