:PROPERTIES:
:ID:       20753ab5-70c3-4c8f-b261-56832cd5392c
:mtime:    20220514132808
:ctime:    20220514130004
:END:
#+title: Trouver le premier élément d'un iterable satisfaisant avec any

* Introduction

Le but est de remplacer le code suivant par une version plus courte à l'aide de la fonction /any/:

#+BEGIN_SRC python :results output
from timeit import timeit
from typing import List, Optional


def get_first_odd(items: List[int]) -> Optional[int]:
    for item in items:
        if item % 2:
            return item
    return None

count = 1_000_000
elapsed = timeit(lambda: get_first_odd([14, 16, 18, 20, 35, 41, 100]), number=count)
print(f'Elapsed time to find the first odd {count} times: {elapsed}.')
#+END_SRC

#+RESULTS:
: Elapsed time to find the first odd 1000000 times: 0.31392509397119284.

#+BEGIN_SRC python :results output
from timeit import timeit
from typing import List, Optional

def get_first_odd(items: List[int]) -> Optional[int]:
    is_odd = lambda x: x % 2
    if any(is_odd(found := item) for item in items):
        return found
    return None

count = 1_000_000
elapsed = timeit(lambda: get_first_odd([14, 16, 18, 20, 35, 41, 100]), number=count)
print(f'Elapsed time to find the first odd {count} times: {elapsed}.')
#+END_SRC

#+RESULTS:
: Elapsed time to find the first odd 1000000 times: 0.9898421700345352.


* Références
 * [[https://docs.python.org/fr/3/library/functions.html#any][Python Built-in Functions]]
 * [[https://mathspp.com/blog/pydonts/boolean-short-circuiting][Boolean short-circuiting - Pydon't]]
