A Common-Sense Guide to Data Structures and Algorithms, Second Edition: number_of_paths implementations are not equivalent (pg. 176/177)

There are two provided implementations for the number_of_paths function. The ‘hardcoded’ version is correct, but the simplified version is not.

pg. 176

def number_of_paths(n):
  return 0 if n <= 0
  return 1 if n == 1
  return 2 if n == 2
  return 4 if n == 3
  return number_of_paths(n - 1) + number_of_paths(n - 2) + number_of_paths(n - 3)
end

pg. 177

def number_of_paths(n):
  return 0 if n < 0
  return 1 if n == 1 || n == 0
  return number_of_paths(n - 1) + number_of_paths(n - 2) + number_of_paths(n - 3)
end

Page 177’s implementation returns 1 instead of 0 for number_of_paths(0).

Thanks for submitting this. While you are correct that the two methods are not identical in this regard, that is by design. I explain there in the text between the two versions that in the simplified version, we are “rigging” the base case of 0 to return 1 for the very sake of simplifying the code. I hope that helps!