7.4k views
4 votes
8.3.5: Max In List

Write the function max_int_in_list that takes a list of ints and returns the biggest int in the list. You can assume that the list has at least one int in it. A call to this function would look like:

my_list = [5, 2, -5, 10, 23, -21]
biggest_int = max_int_in_list(my_list)
# biggest_int is now 23
Do not use the built-in function max in your program!

Hint: The highest number in the list might be negative! Make sure your function correctly handles that case.

2 Answers

0 votes

Final answer:

The function max_int_in_list finds the largest integer in a list by iterating over each element, comparing it to the current maximum, and updating the maximum if necessary. It efficiently handles lists with all negative numbers by returning the least negative number.

Step-by-step explanation:

To write the function max_int_in_list that takes a list of integers and returns the biggest integer without using the built-in max function, you can start by assuming that the first number in the list is the largest. You can then iterate through the list, comparing each number with the current highest number, and updating it as needed when you find a bigger number. Here's one way to implement the function:

def max_int_in_list(lst):

max_int = lst[0]

for number in lst:

if number > max_int:

max_int = number

return max_int

# Example usage:

my_list = [5, 2, -5, 10, 23, -21]

biggest_int = max_int_in_list(my_list)

# biggest_int is now 23

This function works by setting max_int to the first value of lst and then comparing each subsequent integer with max_int, updating max_int if a larger integer is found. It successfully handles lists with all negative numbers as well, returning the least negative number (which is the maximum in a list of negative numbers).

User Tom St
by
3.6k points
3 votes

Final answer:

The function max_int_in_list takes a list of integers as input and returns the largest integer in the list.

Step-by-step explanation:

The function max_int_in_list takes a list of integers as input and returns the largest integer in the list. One way to do this is by iterating over each element in the list and comparing it with a variable that keeps track of the maximum value found so far. If the current element is greater than the maximum value, then update the maximum value. Finally, return the maximum value as the result.

Here is an example implementation of the max_int_in_list function:

def max_int_in_list(lst):
max_num = lst[0]
for num in lst:
if num > max_num:
max_num = num
return max_num

Now, you can call this function with a list of integers and it will return the largest integer in the list.

User Jim Jimson
by
4.6k points