From 0a233decd5a2e48119af0f309db9339d7bcfdc44 Mon Sep 17 00:00:00 2001 From: Colin Date: Wed, 9 Jul 2025 22:16:59 -0400 Subject: [PATCH] Update e02b4_sum_intable.py Replaced the two-function setup with one clear function (sum_ignore) that directly converts and sums int-compatible values. It now handles both ValueError and TypeError, and avoids using sum as a variable name to prevent conflicts with the built-in function. --- ch01-numbers/e02b4_sum_intable.py | 34 ++++++++++++------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/ch01-numbers/e02b4_sum_intable.py b/ch01-numbers/e02b4_sum_intable.py index 21cb9c6..f35b458 100755 --- a/ch01-numbers/e02b4_sum_intable.py +++ b/ch01-numbers/e02b4_sum_intable.py @@ -1,22 +1,14 @@ #!/usr/bin/env python3 -"""Solution to chapter 1, exercise 2, beyond 4: sum intable""" - - -def is_intable(one_item): - try: - int(one_item) - return True - except ValueError: - return False - - -def sum_intable(items): - """Accepts a list of Python objects. - -Sums those objects that are integers or can be -turned into integers. -""" - - return sum(one_item - for one_item in items - if is_intable(one_item)) +# Solution to chapter 1, exercise 2, beyond 4: sum intable +# Write a function that takes a list of Python objects. Sum the objects that either +# are integers or can be turned into integers, ignoring the others. + +def sum_ignore(liste: list): + total = 0 + for number in liste: + try: + valeur = int(number) + total += valeur + except (ValueError, TypeError): + continue + return total