Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i check the time complexity of a comprehension

I have gone through many blogs regarding python time complexity and posting my doubt:

In case of list comprehensions how will the time complexity be analysed?

For example:

x = [(i,xyz_list.count(i)) for i in xyz_set]

where xyz_list = [1,1,1,1,3,3,4,5,3,2,2,4,5,3] and xyz_set = set([1, 2, 3, 4, 5])

So, is the complexity the one line of code O(n*n*n) [i.e., O(n) for iteration, O(n) for list creation, O(n) for count function]??

like image 285
Prem Sagar Gali Avatar asked Feb 08 '15 11:02

Prem Sagar Gali


People also ask

What is the time complexity of list comprehension?

“List comprehension” is not the kind of thing that has “time complexity”. An algorithm which processes an input of size in a particular way can be examined for its running time as a function of . “List comprehension” is a nice syntax for specifying lists. It is not an algorithm.

Does list comprehension reduce time complexity?

If iterations are performed over computationally expensive function, list and for-loop runtime may be almost the same. where a list comprehension and for-loop run time is compared for a simple function of multiples of 2 in each loop. The results showed that list comprehension was twice faster than for-loop.

Does list comprehension reduce time complexity in Python?

List Comprehensions help us in reducing the execution time of a program where you are required to create a list based on any mathematical expression. We will consider an example to prove the above statement.

Why list comprehension is faster than for loop?

As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.


1 Answers

This is quadratic O(n^2):

x = [(i,xyz_list.count(i)) for i in xyz_set]

xyz_list.count(i)) #  0(n) operation

for every i in xyz_set you do a 0(n) xyz_list.count(i)

You can write it using a double for loop which will make it more obvious:

res = []
for i in xyz_set: # 0(n)
    count = 0
    for j in xyz_list: # 0(n)
        if i == j: # constant operation 0(1) 
            count += 1 # constant operation 0(1)
    res.append(count) # constant operation 0(1)

Python time complexity

usually when you see a double for loop the complexity will be quadratic unless you are dealing with some constant number, for instance we just want to check the first 7 elements of xyz_list then the running time would be 0(n) presuming we are doing the same constant work inside the inner for:

sec = 7
res = []
for i in xyz_set: 
    count = 0
    for j in xyz_list[:sec]: 
        ......
like image 131
Padraic Cunningham Avatar answered Oct 07 '22 23:10

Padraic Cunningham