From a8c4795f77c1d28ec2a1e1eaef28086bcbdd448c Mon Sep 17 00:00:00 2001 From: Jez Date: Tue, 24 Sep 2019 11:08:49 -0500 Subject: [PATCH 1/2] Changed the implementation of exercise 3 in python essentials to make it faster, more pythonic and use techniques explained in the text --- source/rst/python_essentials.rst | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/source/rst/python_essentials.rst b/source/rst/python_essentials.rst index 65fc49cf..f892e567 100644 --- a/source/rst/python_essentials.rst +++ b/source/rst/python_essentials.rst @@ -1049,13 +1049,10 @@ Here's one solution: .. code-block:: python3 - def f(string): - count = 0 - for letter in string: - if letter == letter.upper() and letter.isalpha(): - count += 1 - return count - f('The Rain in Spain') + def count_uppercase_chars(s): + return sum([c.isupper() for c in s] + + count_uppercase_chars('The Rain in Spain') Exercise 4 From 6920b87b699ede7f40eea4d832c2f9909c0a17e7 Mon Sep 17 00:00:00 2001 From: Jez Date: Tue, 24 Sep 2019 17:46:04 -0500 Subject: [PATCH 2/2] Reincorporated the original solution as the implementation is easy to understand. The short solution has been left as an alternative. --- source/rst/python_essentials.rst | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/source/rst/python_essentials.rst b/source/rst/python_essentials.rst index f892e567..a54a515e 100644 --- a/source/rst/python_essentials.rst +++ b/source/rst/python_essentials.rst @@ -1047,10 +1047,23 @@ Exercise 3 Here's one solution: +.. code-block:: python3 + + def f(string): + count = 0 + for letter in string: + if letter == letter.upper() and letter.isalpha(): + count += 1 + return count + f('The Rain in Spain') + + +An alternative, more pythonic solution, would be: + .. code-block:: python3 def count_uppercase_chars(s): - return sum([c.isupper() for c in s] + return sum([c.isupper() for c in s]) count_uppercase_chars('The Rain in Spain')