From 3ba6cad899ec4106b84e5296b1c715c244ad511c Mon Sep 17 00:00:00 2001 From: Denis Kazakov <86667459+Denis-Kazakov@users.noreply.github.com> Date: Sat, 6 Sep 2025 12:54:08 +0300 Subject: [PATCH] Update 11_selection.md Fix bug. Code on page 127 in pdf failed with this trace: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[19], line 1 ----> 1 secondsmallest(L) Cell In[18], line 5, in secondsmallest(L) 3 a, b = None, None 4 for item in L: ----> 5 if a is None or item <= b: 6 a, b = item, a 7 elif b is None or item <= a: TypeError: '<=' not supported between instances of 'int' and 'NoneType' --- prose/11_selection.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/prose/11_selection.md b/prose/11_selection.md index 88a69e8..4ec0816 100644 --- a/prose/11_selection.md +++ b/prose/11_selection.md @@ -24,12 +24,16 @@ If our goal is to find the second largest item in a list, we could do this in li ```python def secondsmallest(L): - a, b = None, None - for item in L: - if a is None or item <= b: - a, b = item, a - elif b is None or item <= a: - b = item + if len(L) < 2: + return None + a, b = L[0], L[1] + if a > b: + a, b = b, a + for i in range(2, len(L)): + if L[i] <= a: + a, b = L[i], a + elif L[i] < b: + b = L[i] return b ```