parse_ranges: nouvelle solution

This commit is contained in:
Cacahuete 2020-12-26 23:46:02 +01:00
parent 51ec5db7bc
commit 9ecfc1addc

View file

@ -54,4 +54,42 @@ def parse_ranges_v4(range_string):
yield number
parse_ranges = parse_ranges_v4
def parse_ranges_v5(range_string):
"""Revisiting the solution after reading Trey's answer.
The part 'for (begin, _, end) in [subrange.partition("-")]' is tricky as it is here
to 'iterate' over the one element list and thus assign the 3-tuple we need inside
the comprehension.
Comprehesion are a way to write for loops and the one we want to write is:
ranges = []
for subrange in range_string.split(","):
begin, _, end = subrange.partition("-")
if end.isdecimal():
ranges.append(start, end)
else:
ranges.append(start, start)
Read more here: https://nedbatchelder.com/blog/201802/a_python_gargoyle.html
"""
range_string = range_string.replace("->", "-")
return (
number
for start, stop in (
(begin, end) if end.isdecimal() else (begin, begin)
for subrange in range_string.split(",")
for (begin, _, end) in [subrange.partition("-")]
)
for number in range(int(start), int(stop) + 1)
)
# L'idée principale de la correction est l'expression de générateur :
# (EXPRESSION for NOM in ITERABLE) qui permet de rester 'fainéant' de bout en bout !
#
# Et bien sûr la gargouille for (begin, _, end) in [subrange.partition("-")]
# à utiliser avec modération car la lisibilité compte !
parse_ranges = parse_ranges_v5