[SOLVED] What is the fastest way to find the maximum of an array and another variable?

Issue

I have a list x and another variable y. I want to find the maximum of all the elements from x and y combined. Which of these runs fastest?

  1. max(*x, y)
  2. max(max(x), y)
  3. max(x+[y])
  4. First find k=max(x) and then find maximum of k and y using if else statement

Here’s the code and timeit results:

import timeit

setup_="""\
x = [1,2,3,4,5]
y = 6
"""

s="""\
max(*x, y)
"""
print(timeit.timeit(setup=setup_, stmt=s))

x = [1,2,3,4,5]
y = 6
s="""\
max(max(x), y)
"""
print(timeit.timeit(setup=setup_, stmt=s))

x = [1,2,3,4,5]
y = 6
s="""\
max(x+[y])
"""
print(timeit.timeit(setup=setup_, stmt=s))


x = [1,2,3,4,5]
y = 6
s="""\
k=max(x)
if k>=y:
    max_ = k
else:
    max_ = y
"""
print(timeit.timeit(setup=setup_, stmt=s))
0.5596736
0.4779417
0.5439717
0.3297147

Are there any faster ways than the above methods?

Solution

The best method could be found out by implementing the timeit python.

I am giving out the timing for each of your program, and you will see which one is best

import timeit

# Taking x = [1,2,3,4,5] and y = 8
print(timeit.timeit('max([1,2,3,4,5], [8])', number=10000))
print(timeit.timeit('max(max([1,2,3,4,5]), 8)', number=10000))
print(timeit.timeit('max([1,2,3,4,5]+[8])', number=10000))

Output

0.003129853866994381                                                                                                                   
0.0323555301874876                                                                                                                     
0.007466199807822704

Your first idea is the best one max(x, [y]). 4th point is equivalent to the second point hence it was not taken into consideration. Hope that helps.

Answered By – Alok

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *