这是我遇到的学校问题。我写了我的代码,它返回正确的结果。但是,测试程序显示校验和不匹配。下面是问题和我的代码。在
An element of items is said to be a "dominator" if every element to its right is strictly smaller than it. This function should count how many elements in the given list of items are dominators, and return that count. For example, in the list [42, 7, 12, 9, 2, 5], the elements 42, 12, 9 and 5 are dominators. By this definition, the last item of the list is automatically a dominator.
def count_dominators(items):
if len(items) ==0:
return len(items)
else:
k = 1
for i in range(1,len(items)):
if items[i]<items[i-1]:
k = k+1
else:
k = k+0
return k
就像已经在评论中提到的,你没有比较操作是不正确的。当前您正在比较:
如果条件成立,增加k值。根据你的任务,支配者被定义为“其右边的每一个元素都严格小于它”。这意味着您必须将每个项目与其右侧的每个元素进行比较(即,您必须检查42>;7、42>;12、42>;9、42>;2和42>;5,以确定42是否为支配者)。在
看看下面的函数:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐