擅长:python、mysql、java
<p>假设<code>return False</code>在for循环之外,否则只有在发送包含1个元素的列表时才会出现错误。你知道吗</p>
<p>问题是,当您发送一个递减列表(或一个包含1个元素的列表)时,您一直在迭代,直到<code>j</code>成为最后一个元素(即<code>len(heights) - 1)</code>)的索引,因此当您尝试访问<code>heights[j + 1]</code>时,它会出现<code>IndexError:List index out of range</code>错误。你知道吗</p>
<p>您应该只从<code>0</code>到<code>len(heights) - 2</code>进行迭代,您可以使用range函数(在range中,您应该给出<code>len(heights) -1</code>),因为range不包括i时的最后一个元素</p>
<p>示例-</p>
<pre><code>def is_monotone(heights):
if len(heights) == 0:
return True
for j in range(len(heights)-1):
if heights[j + 1] >= heights[j]:
return True
return False
</code></pre>
<hr/>
<p>但是,如果函数检查的是列表是否单调递增(所有元素都递增),那么您的逻辑有点不正确,当您发现下一个元素的单个实例大于第一个元素时,不应返回True。你知道吗</p>
<p>相反,当您在连续索引中发现一个数字递减的实例时,应该返回false,而在for循环外返回True。请注意,只有当你的功能是检查数字是否在一个递增的序列。你知道吗</p>
<p>示例-</p>
<pre><code>def is_monotone(heights):
if len(heights) == 0:
return True
for j in range(len(heights)-1):
if heights[j + 1] < heights[j]:
return False
return True
</code></pre>