Josh Carp
Josh Carp

Reputation: 13

Hi i am new to python and was wondering how do i find the max value in my search algorithm?

Hi so im currently taking discrete structures and algorithm course and have to work with python for the first time so im having a little trouble getting my function find the max value in the list can you take a look at my code because im trying to also convert to pseudocode:


def max_search(numbers):
    numbers = [1, 5, 9, 3, 4, 6]

    max = numbers = [0]

    for i in range(1, len(numbers)):
        if numbers[i] > max:
            max = numbers[i]

    max_search(numbers)
    print(max)

Upvotes: 0

Views: 44

Answers (3)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

When you write the code for maximum number in a list, start by thinking of base cases, which will be.

  1. Maximum can be pre-defined constant, say -1 if the list is empty
  2. Maximum is the first element in the list, if the list only has one element.

After that, if the list is longer, you assign the first element of the list as maximum, and then you iterate through the list, updating the maximum if you find a number which is greater than the maximum.

def max_search(numbers):

    #Maximum of an empty list is undefined, I defined it as -1
    if len(numbers) == 0:
        return -1
    #Maximum of a list with one element is the element itself
    if len(numbers) == 1:
        return numbers[0]

    max = numbers[0]
    #Iterate through the list and update maximum on the fly
    for num in numbers:
        if num >= max:
            max = num

    return max

In your case, you are overwriting the numbers argument with another list inside the function [1, 5, 9, 3, 4, 6], and you are recursively calling the same functions with same arguments, which will lead to Stack Overflow

Upvotes: 0

Saurabh kukade
Saurabh kukade

Reputation: 1634

I have made some changes

def max_search(numbers):

    max = -1 # if numbers contains all positive number

    for i in range(len(numbers)):
        if numbers[i] > max:
            max = numbers[i]

max = max_search([1, 5, 9, 3, 4, 6])
print(max)

Upvotes: 0

vb_rises
vb_rises

Reputation: 1907

Use the max method provided for list

max(numbers)

Upvotes: 1

Related Questions