DEV Community

Kuldeep Singh
Kuldeep Singh

Posted on

[Python] Find the Largest Number From a Array.

In this article we're about to code to get the largest number from array using python.

Algorithm can't be easy it take time to learn but everyone can learn it how via learning and implementing it, Without implementing algorithms by our own it always seems hard but we should try, to avoid that hesitation let's start writing code



def largest( arr, n):
    large = 0
    for x in range(0,n):
        if arr[x] >= large:
            large = arr[x]
            continue
    print(large)


Enter fullscreen mode Exit fullscreen mode

so what we've done in the code let's explore one by one

  1. we've created a function which takes two arguments, first array of integers and second is the length of the array.
  2. created a variable which is used to hold the largest value
  3. we're running loop and inside loop we're checking if large variable is less then arr[x] then updating the value of large

For More and you can subscribe me:
https://kdsingh4.blogspot.com/

Top comments (4)

Collapse
 
patricktingen profile image
Patrick Tingen

Why reinvent a wheel when you already have one?

def largest(arr):  
    arr.sort(reverse=True)
    if len(arr) > 0:
        return arr[0]
    else:
        return 0

numbers = [1, 3, 4, 2]
print(largest(numbers))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jayjeckel profile image
Jay Jeckel

The passed array doesn't need to be changed and shouldn't be changed by a method that only needs to look at its contents. You've added a side effect to a method that shouldn't have any side effects. Other than a few nitpicks, the article's example of the method is the correct way of doing it.

Collapse
 
hunter profile image
Hunter Henrichsen • Edited
numbers = [1, 3, 4, 2]
print(max(numbers))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
eshu profile image
Eshu

What the complexity of sort? :)