python generators time complexity confusion

2024/11/17 10:50:28

I have been reading about keyword yield and generators in python and I want to know if I have understood it right it terms of time complexity.

Here is my generator function to get factors:

def calc_factors(n):for k in range(0, n+1):     # this is the second "for" loopif n % k == 0:yield k

and I would call this generator function as:

>>> for factor in calc_factor(100):   # this is the first "for" loopprint factor

Now my understanding is that this has time complexity of O(n^2) as it has two for loops but again I'm not convinced. Please enlighten me on this front. Thanks in advance!

Answer

You misunderstood. You have a O(n) loop. The loop over the generator function is not a nested loop, it merely receives each item from the generator as it is yielded.

In other words, the for factor in calc_factor(100) loop is directly connected to the yield k expression; each time that executes the for factor in calc_factor(100) loop advances one step. You get 1 factor value for every yield k expression executed. yield k executes (up to) n times, no more.

You can, without bending the truth too much, imagine all code in the for factor in calc_factor(100) loop body as replacing the yield k line, with factor = k. In your case you only use print factor, so you could replace the yield k with print k with no loss of functionality.

If you want to look at it differently, take away the generator and build a list. This is what your code does in that case:

results = []
for k in range(0, n+1):if n % k == 0:results.append(k)for factor in results:print factor

Now you have two loops still, but they are not nested. One is a O(n) loop to build the list, the other is a O(k) loop (with k < n) to print the results. This would still be a O(n) algorithm; constant multipliers are ignored (you'd have O(2n) -> O(n)).

All the generator does is remove the intermediary list. You don't have to first collect all the results, you get to have access to each result immediately.

https://en.xdnf.cn/q/71561.html

Related Q&A

Python: Find Amount of Handwriting in Video

Do you know of an algorithm that can see that there is handwriting on an image? I am not interested in knowing what the handwriting says, but only that there is one present? I have a video of someone…

Include nonce and block count in PyCrypto AES MODE_CTR

Some background information, you can skip this part for the actual questionthis is my third question about this topic here at stackoverflow. To be complete, these are the other questions AES with crypt…

Why is pandas.series.map so shockingly slow?

Some days I just hate using middleware. Take this for example: Id like to have a lookup table that maps values from a set of inputs (domain) values, to outputs (range) values. The mapping is unique. A …

Viewset create custom assign value in Django Rest Framework

Would like to set a CustomUsers username by using the input email, but where to do the custom assigning, in view? At the same time it receiving a file as well.Models.pyclass CustomUser(AbstractUser):a…

Remove a relation many-to-many (association object) on Sqlalchemy

Im stuck with a SqlAlchemy problem.I just want to delete an relation. This relation is made by an association object.modelsclass User(db.Model, UserMixin):id = db.Column(db.Integer, pr…

Spark Dataframes: Skewed Partition after Join

Ive two dataframes, df1 with 22 million records and df2 with 2 million records. Im doing the right join on email_address as a key. test_join = df2.join(df1, "email_address", how = right).cach…

Caught TypeError while rendering: __init__() got an unexpected keyword argument use_decimal

While running the program i am getting the following error messageCaught TypeError while rendering: __init__() got an unexpected keyword argument use_decimalHere is my code i am using jquery 1.6.4 d…

How to get chunks of elements from a queue?

I have a queue from which I need to get chunks of 10 entries and put them in a list, which is then processed further. The code below works (the "processed further" is, in the example, just pr…

Receiving commandline input while listening for connections in Python

I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this…

Passing a parameter through AJAX URL with Django

Below is my code. n logs correctly in the console, and everything works perfectly if I manually enter the value for n into url: {% url "delete_photo" iddy=2%}. Alas, when I try to use n as a …