Max of Three¶

An exploration of the multiple ways of finding the maximum of three numbers.

Question to you, which one is best?

# This is our template for a bunch of our examples below
def max_num():
input_str = input("Please enter three values (x1,x2,x3): ")

# These two lines are used instead of eval()
x1, x2, x3 = input_str.split(",")
x1, x2, x3 = int(x1), int(x2), int(x3)

# Missing code here...

print("The largest value is {0}".format(max_))

Strategy #1: Compare Each Number to All¶

• Worst Case: 4 comparisons to determine x1, x2 are smaller than x3.
• Best Case: 2 comparisons are made to determine that x1 is the largest number.

* We make the decision that x1 is the first number we check.

Strategy #2: Decision Tree¶

• Worst Case: 2 comparisons to determine x1, x2 are smaller than x3.
• Best Case: 2 comparisons to determine x1 is the largest number.

* We make the decision that x1 is the first number we check.

What if you wanted to compare 4 or more numbers?¶

This quickly becomes an ugly and unmanageable problem. We get seriously messy code.

Strategy #3 : Sequential Programming¶

• Worst Case: 2 comparisons to determine x1, x2 are smaller than x3.
• Best Case: 2 comparisons to determine x1 is the largest number.

What if you wanted to compare 4 or more numbers with this sequential method?¶

It now becomes easy to do and read.

What if you wanted to compare $n$ numbers with this sequential method? For example, 100 numbers?¶

It now becomes easy to do and read.