Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions python-min-and-max/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Python's min() and max(): Find Smallest and Largest Values

This folder provides the code examples for the Real Python tutorial [Python's min() and max(): Find Smallest and Largest Values](https://realpython.com/python-min-and-max/).

## Setup

The scripts only use the standard library, so there's nothing to install. The tutorial's code was tested with Python 3.13.

## Usage

You can run each script directly by specifying its name:

```sh
$ python <filename>.py
```

Each script collects one section of the tutorial, in the order the tutorial presents it:

| Script | Tutorial section |
| --- | --- |
| [`getting_started.py`](./getting_started.py) | Getting Started With Python's `min()` and `max()` Functions |
| [`strings.py`](./strings.py) | Using `min()` and `max()` With Strings and Iterables of Strings |
| [`dictionaries.py`](./dictionaries.py) | Processing Dictionaries With `min()` and `max()` |
| [`key_and_default.py`](./key_and_default.py) | Tweaking the Standard Behavior of `min()` and `max()` With `key` and `default` |
| [`comprehensions.py`](./comprehensions.py) | Using `min()` and `max()` With Comprehensions and Generator Expressions |
| [`practical_examples.py`](./practical_examples.py) | Putting Python's `min()` and `max()` Into Action |
| [`person.py`](./person.py), [`comparison_methods.py`](./comparison_methods.py) | Exploring the Role of `.__lt__()` and `.__gt__()` in `min()` and `max()` |
| [`find_min_max.py`](./find_min_max.py) | Understanding the Code Behind `min()` and `max()` |
| [`min_max.py`](./min_max.py) | Emulating Python's `min()` and `max()` |

You can also import the custom functions from `min_max.py` in a REPL session:

```pycon
>>> from min_max import custom_max, custom_min

>>> custom_min([3, 5, 9, 1, -5])
-5

>>> custom_max(["20", "3", "35", "7"], key=int)
'35'
```

## A Note on the Examples

Most of the tutorial's examples are REPL sessions. In the scripts, values that the REPL would echo are passed to `print()`, and strings are printed with `repr()` so that the output matches the quoted form the REPL shows. Examples that raise an exception on purpose catch it and print the error message instead. The timings in `practical_examples.py` depend on your computer, so they'll differ from the ones in the tutorial.
38 changes: 38 additions & 0 deletions python-min-and-max/comparison_methods.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from person import Person

# Built-in types implement .__lt__() and .__gt__()
for data_type in (int, float, str, list, tuple, dict):
print(
data_type.__name__,
"__lt__" in dir(data_type) and "__gt__" in dir(data_type),
)

# Custom classes that implement .__lt__() and .__gt__()
jane = Person("Jane Doe", "2004-08-15")
john = Person("John Doe", "2001-02-07")

print(jane < john)
print(jane > john)

print(min(jane, john))
print(max(jane, john))


# Custom classes that don't implement .__lt__() and .__gt__()
class Number:
def __init__(self, value):
self.value = value


x = Number(21)
y = Number(42)

try:
min(x, y)
except TypeError as error:
print(f"TypeError: {error}")

try:
max(x, y)
except TypeError as error:
print(f"TypeError: {error}")
15 changes: 15 additions & 0 deletions python-min-and-max/comprehensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
letters = ["A", "B", "C", "X", "Y", "Z"]

# List comprehensions
print(repr(min(letters)))
print(repr(min([letter.lower() for letter in letters])))

print(repr(max(letters)))
print(repr(max([letter.lower() for letter in letters])))

# The key argument instead of a comprehension
print(repr(min(letters, key=str.lower)))

# Generator expressions
print(repr(min(letter.lower() for letter in letters)))
print(repr(max(letter.lower() for letter in letters)))
18 changes: 18 additions & 0 deletions python-min-and-max/dictionaries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
prices = {
"banana": 1.20,
"pineapple": 0.89,
"apple": 1.57,
"grape": 2.45,
}

print(repr(min(prices)))
print(repr(max(prices)))

print(repr(min(prices.keys())))
print(repr(max(prices.keys())))

print(min(prices.values()))
print(max(prices.values()))

print(min(prices.items()))
print(max(prices.items()))
18 changes: 18 additions & 0 deletions python-min-and-max/find_min_max.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def find_min(iterable):
minimum = iterable[0]
for value in iterable[1:]:
if value < minimum:
minimum = value
return minimum


def find_max(iterable):
maximum = iterable[0]
for value in iterable[1:]:
if value > maximum:
maximum = value
return maximum


print(find_min([2, 5, 3, 1, 9, 7]))
print(find_max([2, 5, 3, 1, 9, 7]))
32 changes: 32 additions & 0 deletions python-min-and-max/getting_started.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Calling min() and max() with a single iterable argument
print(min([3, 5, 9, 1, -5]))
print(max([3, 5, 9, 1, -5]))

try:
min([])
except ValueError as error:
print(f"ValueError: {error}")

try:
max([])
except ValueError as error:
print(f"ValueError: {error}")

# Mixing integers and floating-point numbers
print(min([3, 5.0, 9, 1.0, -5]))
print(max([3, 5.0, 9, 1.0, -5]))

# Mixing numbers and strings doesn't work
try:
min([3, "5.0", 9, 1.0, "-5"])
except TypeError as error:
print(f"TypeError: {error}")

try:
max([3, "5.0", 9, 1.0, "-5"])
except TypeError as error:
print(f"TypeError: {error}")

# Calling min() and max() with multiple arguments
print(min(3, 5, 9, 1, -5))
print(max(3, 5, 9, 1, -5))
8 changes: 8 additions & 0 deletions python-min-and-max/key_and_default.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
print(repr(min(["20", "3", "35", "7"])))
print(repr(max(["20", "3", "35", "7"])))

print(repr(min(["20", "3", "35", "7"], key=int)))
print(repr(max(["20", "3", "35", "7"], key=int)))

print(min([], default=42))
print(max([], default=42))
50 changes: 50 additions & 0 deletions python-min-and-max/min_max.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from operator import gt, lt


def min_max(*args, operator, key=None, default=None):
if len(args) == 1:
try:
values = list(args[0]) # Also check if the object is iterable
except TypeError:
raise TypeError(
f"{type(args[0]).__name__} object is not iterable"
) from None
else:
values = args

if not values:
if default is None:
raise ValueError("args is an empty sequence")
return default

if key is None:
keys = values
else:
if callable(key):
keys = [key(value) for value in values]
else:
raise TypeError(f"{type(key).__name__} object is not a callable")

extreme_key, extreme_value = keys[0], values[0]
for key, value in zip(keys[1:], values[1:]):
if operator(key, extreme_key):
extreme_key = key
extreme_value = value
return extreme_value


def custom_min(*args, key=None, default=None):
return min_max(*args, operator=lt, key=key, default=default)


def custom_max(*args, key=None, default=None):
return min_max(*args, operator=gt, key=key, default=default)


if __name__ == "__main__":
print(custom_min([3, 5, 9, 1, -5]))
print(custom_max(3, 5, 9, 1, -5))
print(repr(custom_min(["20", "3", "35", "7"], key=int)))
print(repr(custom_max(["20", "3", "35", "7"], key=int)))
print(custom_min([], default=42))
print(custom_max([], default=42))
19 changes: 19 additions & 0 deletions python-min-and-max/person.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from datetime import date


class Person:
def __init__(self, name, birth_date):
self.name = name
self.birth_date = date.fromisoformat(birth_date)

def __repr__(self):
return (
f"{type(self).__name__}"
f"({self.name}, {self.birth_date.isoformat()})"
)

def __lt__(self, other):
return self.birth_date > other.birth_date

def __gt__(self, other):
return self.birth_date < other.birth_date
77 changes: 77 additions & 0 deletions python-min-and-max/practical_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import math
import timeit

# Removing the smallest and largest numbers in a list
sample = [4, 5, 7, 6, -12, 4, 42]
sample.remove(min(sample))
print(sample)
sample.remove(max(sample))
print(sample)

# Building lists of minimum and maximum values
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([min(x) for x in matrix])
print([max(x) for x in matrix])

# Clipping values to the edges of an interval
upper = 100
numbers = [42, 78, 200, -230, 25, 142]
print([min(number, upper) for number in numbers])

lower = 10
numbers = [42, 78, 200, -230, 25, 142]
print([max(number, lower) for number in numbers])

lower, upper = 10, 100
numbers = [42, 78, 100, -230, 25, 142]
print([max(min(number, upper), lower) for number in numbers])

# Finding the closest points
point_pairs = [
((12, 5), (9, 4)),
((2, 5), (3, 7)),
((4, 11), (15, 2)),
]
print(min(point_pairs, key=lambda points: math.dist(*points)))

# Identifying cheap and expensive products
prices = {
"banana": 1.20,
"pineapple": 0.89,
"apple": 1.57,
"grape": 2.45,
}
print(min(prices.items(), key=lambda item: item[1]))
print(max(prices.items(), key=lambda item: item[1]))


# Finding coprime integer numbers
def are_coprime(a, b):
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
return False
return True


print(are_coprime(2, 3))
print(are_coprime(2, 4))

# Timing different implementations of your code
print(
min(
timeit.repeat(
stmt="[i ** 2 for i in range(100)]",
number=1000,
repeat=3,
)
)
)
print(
min(
timeit.repeat(
stmt="list(map(lambda i: i ** 2, range(100)))",
number=1000,
repeat=3,
)
)
)
18 changes: 18 additions & 0 deletions python-min-and-max/strings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
print(repr(min("abcdefghijklmnopqrstuvwxyz")))
print(repr(max("abcdefghijklmnopqrstuvwxyz")))

print(repr(min("abcdWXYZ")))
print(repr(max("abcdWXYZ")))

# UTF-8 characters
print(repr(min("abc123ñ")))
print(repr(max("abc123ñ")))

print(ord("A"))
print(ord("a"))

print(repr(min("aA")))
print(repr(max("aA")))

print(repr(min(["Hello", "Pythonista", "and", "welcome", "world"])))
print(repr(max(["Hello", "Pythonista", "and", "welcome", "world"])))
Loading