문제

I am a beginner at Python, and this is my first post, so don't be too harsh :). I've been playing around with Python lately and was wondering if something like

max([x for x in range(25)]) 

would result in Python first creating a list of all the elements and then finding the max, resulting in O(2n) time, or it would keep track of the max as it was iterating for Θ(n). Also, since range differs in Python3 (being a iterable), would that make it different than in Python2?

도움이 되었습니까?

해결책

Your example will result in Python first building the entire list. If you want to avoid that, you can use a generator expression instead:

max((x for x in range(25)))

or simply:

max(x for x in range(25))

Of course (in Python 2), range itself builds an entire list, so what you really want in this case is:

max(x for x in xrange(25))

However, regarding the time taken, all these expressions have the same complexity. The important difference is that the last one requires O(1) space, whereas the others require O(n) space.

다른 팁

List comprehensions always generate a list (unless something throws an exception). Use of a genex instead is recommended in most cases.

max(x for x in xrange(25))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top