[DSA in Python] minmax.py

This was the third exercise of Chapter 1 (Python Primer) in the book 'Data Structures and Algorithms in Python' by Goodrich et al.

Problem: "Write a short Python function, minmax(data), that takes a sequence of one or more numbers, and returns the smallest and largest numbers, in the form of a tuple of length two. Do not use the built-in functions min or max in implementing your solution."

Potential Solution:
The obvious solution to getting the min and max of a sequence would be to use the Python built-in functions min and max:

However, we cannot use these built-in functions from Python. An alternative approach would be to use a for loop:

In this function, we set two variables to the first element of the sequence, data. We then proceed iterate through the sequence, data, through indexing. Within the for loop, we make two checks. If the variable smallest's value is larger than the current element, data[i], then that must mean that the current element is the smallest at this moment in the loop. A similar comparison is made for the largest number, instead we check if the variable largest's value is smaller than the current element, data[i].

  • In a function, Python can return two or more variables. It can do this by returning a sequence of these variables. However, this sequence is a tuple, not a list. The difference between a tuple and a list is that elements cannot be modified in tuple whereas elements can be changed in a list.