3 ms·
Is it just me, or is the get_temp function wrong? Indentation error on the return statement?
by rrauenza 4y ago
Is it just me, or is the get_temp function wrong? Indentation error on the return statement?
- eesmith 4y agoNo, not just you. Here's the code I see: def get_temp(sorted_temps: list[float], el: float) -> int: """ Search through the sorted temperatures array to find the index of the temperature that matches the element :param sorted_temps: sorted list of temperatures :param el: the target element :return: the index of the matched element Author: Richard Hendricks """ i = 0 while el != sorted_temps[i] and len(sorted_temps) > i): i += 1 return i if i < len(sorted_temps) else -1; Some problems I see: 1. the `return ...` line needs to be dedented, otherwise, if `el == sorted_temps[0]` then the return value is None 2. even if dedented, the docstring needs to report that get_temp() returns -1 if the index isn't found 3. there's an extra `)` in `> i):`, and the semi-colon is unneeded 4. the test for `len(sorted_temps) > i` must done before `el != sorted_temps[i]`, The corrected version would be: def get_temp(sorted_temps: list[float], el: float) -> int: i = 0 while len(sorted_temps) > i and el != sorted_temps[i]: i += 1 return i if i < len(sorted_temps) else -1 Furthermore, here are some alternatives: 5. I would expect the following to be faster, and more easily understood: for i, temp in enumerate(sorted_temps): if temp == el: return i return -1 5. Or since the type signature says it's supposed to be a list of floats: try: return sorted_temps.index(el) except ValueError: return -1 6: Or, since the values are supposed to be a sorted list, perhaps a binary search: import bisect i = bisect.bisect_left(sorted_temps, el) if sorted_temps[i] == el: return i return -1