pythonpython-3.xlisttime-complexitybig-o

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


Solution

  • 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