user5368329
user5368329

Reputation:

Finding the maximum number in a list python 3

Below is my code to return the maximum number in the list, but for some reason it returns 9.

I must clarify that the aim of this program is to compare BigO complexities of quadratic - O(n^2) with Linear O(n) . So I am looking for a way to solve this problem with nested loop which will represent O(n^2). Please give a nested loop solution

a = [2,4,7,2,1,9,33,105,2,3,7,300,4,9]
maxa = a[0]
for i in a:
    for j in a:
        if (i>j):
            maxa = i
print("greatest number is   " + str(maxa))

help figure what the problem is

Upvotes: -1

Views: 4828

Answers (5)

pham tue lam
pham tue lam

Reputation: 19

Just use the max function, which should return the maximum number in a list.

L = [2,4,7,2,1,9,33,105,2,3,7,300,4,9]
print(max(L))

Upvotes: 1

Shrihari
Shrihari

Reputation: 123

a = [2,4,7,2,1,9,33,105,2,3,7,300,4,9]
print(max(a))

Output
#300

Explanation: The method max() returns the largest of its arguments: the value closest to positive infinity.

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55499

Your code doesn't find the correct maximum, it simply sets maxa to the last value of i which is greater than some other item in the list.

Here's code that finds the correct maximum using a double loop, as requested, but the j loop is completely pointless.

a = [2, 4, 7, 2, 1, 9, 33, 105, 2, 3, 7, 300, 4, 9]
maxa = a[0]
for i in a:
    for j in a:
        if i > j and i > maxa:
            maxa = i

print("greatest number is", maxa)

output

greatest number is 300

FWIW, you could also write that test as

if i >= j >= maxa:

Here's an even worse way, although it's still quadratic. We scan through the list, swapping an item with the last list item if it's smaller than the item currently there. At the end of the scan, the item at the end of the list must be the minimum, so we discard it. We repeat this process until only a single item remains, and that must be the maximum.

a = [2, 4, 7, 2, 1, 9, 33, 105, 2, 3, 7, 300, 4, 9]
while len(a) > 1:
    for j, u in enumerate(a):
        if u < a[-1]:
            # Move this item to the end of the list
            a[j], a[-1] = a[-1], a[j]
        # The last item is the minimum, so we discard it
        del a[-1]

# Only 1 item is left, it must be the maximum of the original list
print("greatest number is", a[0])

output

greatest number is 300

Upvotes: 1

Amir Naimi
Amir Naimi

Reputation: 143

a = [2,4,7,2,1,9,33,105,2,3,7,300,4,9]
maxa = a[0]
for i in a:
    if i > maxa:
        maxa = i
print(maxa)

Upvotes: 0

Giordano
Giordano

Reputation: 5580

You can simply use the max function.

>>> a = [2,4,7,2,1,9,33,105,2,3,7,300,4,9]
>>> max(a)
>>> 300

Upvotes: 3

Related Questions