English 中文(简体)
1. 最大(清单)与清单中最大(ele1,ele2)对每一要素进行比较
原标题:max(list) vs comparing each element with max(ele1,ele2) in list iteration

请允许我说,为了从名单上获得最大分类,我可以采用以下两种方法:

1)

x = max(arr)

b)

x = 0
for ele in arr:
    x = max(x,ele)

我现在想知道,每种方法的绩效如何? 以及哪一个更快? 时间和空间的复杂性是什么? 谁喜欢?

额外<代码>max(x, ele)比<代码>max(r)更复杂时间的比较? 或反之亦然?

================================================================================================================================================================================================================================================================

edited 8/26/23 now everyone says first one is faster, how about in the example below ?

given a list arr = [1,6,0,9,3,12,8,5], I wanna make a new list from all elements inside arr that the elements can divide by 3, and keep track of the max element in it.

1)


newArr = []
for ele in arr:
    if ele%3 == 0:
        newArr.append(ele)
x = max(newArr) #now newArr should be [6,0,9,3,12]

b)

newArr = []
x = 0
for ele in arr:
    if ele%3 == 0:
        newArr.append(ele)
        if ele > x:   #would x = max(x, ele) cause more time complexity ?
            x = ele

如今,在这种例子中,第2条办法是否不太复杂,因为它只是一次重复使用,而比较了吗? 由于O(n)越高,第1条办法是否更复杂?

I did the test like @KellyBundy did, seems like if ele > x: x = ele is way faster than x = max(x, ele), and little bit faster than max(newArr), see result below.

https://perfpy.com/433

另一项测试也采用了宽松清单,这一次最大程度要快得多。

https://perfpy.com/436

但是,当我与另一个汇编者一起工作时,结果并没有大不相同,令人非常感兴趣的是我利用方案在线汇编者汇编的法典。

https://dpaste.org/UPFWB

问题回答

In terms of time complexity, both methods have the same linear time complexity O(n). However, the first method (max(arr))might have a slight advantage in terms of performance, as it uses a single function optimized for this task, whereas the second method involves a loop with multiple comparisons in each iteration. The actual performance difference might be negligible for small lists, but for larger lists, the first method might be slightly faster due to its optimized nature.

因此,你更喜欢使用“<代码>max(r)功能”,因为功能是为这一特定目的设计的,而且很可能是完全优化的。

Times for 100000 elements (random, increasing or decreasing) with your two ways and one without using max at all:

random
  1.79 ± 0.02 ms  selfmade
  2.04 ± 0.02 ms  just_max
 17.62 ± 0.50 ms  repeated_max

increasing
  1.89 ± 0.01 ms  selfmade
  2.09 ± 0.04 ms  just_max
 17.23 ± 0.09 ms  repeated_max

decreasing
  1.76 ± 0.04 ms  selfmade
  2.06 ± 0.03 ms  just_max
 18.11 ± 0.46 ms  repeated_max

Python: 3.11.4 (main, Jun 24 2023, 10:18:04) [GCC 13.1.1 20230429]

图瓦卢

def just_max(arr):
    x = max(arr)
    return x

def repeated_max(arr):
    x = 0
    for ele in arr:
        x = max(x,ele)
    return x

def selfmade(arr):
    x = 0
    for ele in arr:
        if ele > x:
            x = ele
    return x


funcs = just_max, repeated_max, selfmade

import random
from timeit import timeit
from statistics import mean, stdev
import sys

def test(label, arr):
    print(label)
    times = {f: [] for f in funcs}
    def stats(f):
        ts = [t * 1e3 for t in sorted(times[f])[:5]]
        return f {mean(ts):6.2f} ± {stdev(ts):4.2f} ms  

    for _ in range(25):
        for f in funcs:
            t = timeit(lambda: f(arr), number=1)
            times[f].append(t)

    for f in sorted(funcs, key=stats):
        print(stats(f), f.__name__)

    print()

n = 10**5
test( random , random.choices(range(10**9), k=n))
test( increasing , list(range(n)))
test( decreasing , list(range(n)[::-1]))

print( Python: , sys.version)

在业绩和复杂性方面,要打破两种方法:

<<>Method 1: Usingmax(arr)

这种方法使用<条形码>最大()的沙捞越功能,在内部通过该清单进行调节,并跟踪所达到的最高值。 它为找到最高价值提供了简明和可读的方法。

  • Time Complexity: O(n), where n is the number of elements in the list. The max() function needs to go through each element of the list once to find the maximum.
  • Space Complexity: O(1), because only a constant amount of additional memory is required to keep track of the maximum value.

<>Method2:

这种方法通过清单进行人工调节,并将每个要素与现有最高值进行比较。 如果现有要素更大,则更新上限。

  • Time Complexity: O(n), same as the previous method. It iterates through each element once and performs a constant-time comparison.
  • Space Complexity: O(1), similar to the previous method. Only a few extra variables are used.

这两种方法都具有同样的复杂性,但是在“顶端”(max(>)功能中,可能有一些最佳业绩,由于在C实施,实际上可能使其稍快。 然而,如你提供的小型清单,差异可能并不明显。

In terms of which one is preferred, using max(arr) is generally recommended due to its simplicity, readability, and potential performance optimizations. It s a clear and concise way to express the intention of finding the maximum value in the list. The manual comparison method might be useful in specific cases where you need more control over the comparison process or if you want to perform additional operations during the iteration.

总之,这两种方法在时间方面和空间的复杂性上都相当可观,以便在清单中找到最高价值。 <代码>max()功能通常是首选功能,除非有具体理由人工操作和比较。 手册方法的比较数量与内在功能相比,没有显著影响时间的复杂性。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签