Finding the Max

Read Time:1 Minute, 32 Second

If we are presented with a list of different numbers, how will we identify the largest one? This question sounds straightforward. Using simple arithmetic, we can easily compare different values inside the list and get the largest one. But what if the numbers get more extensive and the list length gets too long to handle?

Considering a scenario, we want to create a list of 30 (or any) random numbers from 1 to 999,999,999 (or even larger). We can use the following code in Python to do so:

Output:

[267136412, 214336632, 125691926, 726317137, 688133647, 906784464, 672440241, 736868097, 182925267, 563311717, 958597941, 438885159, 51618134, 750181003, 773495762, 555368132, 903843296, 302249809, 225543484, 24863368, 954082128, 886720512, 518911521, 875260184, 53528829, 662332800, 842587985, 959819653, 154653148, 259203759]

Now we have the list, so what’s next? It’s so apparent; use the max function to get the answer. But as we were typing the code, we soon realized that there could be more than one way of doing it. Let’s look at some of the possible solutions here.

Using Max Function

Using Sorted Function

You can also use sort() instead, which will replace the original list.

Using For Loop

Using Recursion

And there is more.

As we have seen, one problem already has four different approaches here. The beauty of divergent thinking is innate in programming. Before we start following a path, we should generate various solutions to a problem instead of picking just one. The final answer we agreed on at the end may depend on the focus and constraints of our project.

So far, I cannot tell the pros and cons of these four methods and which runs best under a particular situation. It may have something to do with the analysis of algorithms (Big-O analysis). We will revisit this when we touch on the topic.