数一数“主宰者”

2024-06-15 00:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我遇到的学校问题。我写了我的代码,它返回正确的结果。但是,测试程序显示校验和不匹配。下面是问题和我的代码。在

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.

Click here: The expected result

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

Tags: oftheto代码inlenreturnif
1条回答
网友
1楼 · 发布于 2024-06-15 00:26:52

就像已经在评论中提到的,你没有比较操作是不正确的。当前您正在比较:

  • 比较7<;42
  • 比较12<;7
  • 比较9<;12
  • 比较2<;9
  • 比较5<;2

如果条件成立,增加k值。根据你的任务,支配者被定义为“其右边的每一个元素都严格小于它”。这意味着您必须将每个项目与其右侧的每个元素进行比较(即,您必须检查42>;7、42>;12、42>;9、42>;2和42>;5,以确定42是否为支配者)。在

看看下面的函数:

def count_dominators(items):
    k = 0
    for idx,item in enumerate(items):
        dominator = True
        for ritem in items[idx+1:]:
            print('comparing {} and {}'.format(item, ritem))
            #If True not a dominator
            if item<=ritem:
                dominator = False
                break
        if dominator:
            print('{} is a dominator'.format(item)) 
            k = k+1        
    return k

count_dominators([42, 7, 12, 9, 2, 5])

输出:

^{pr2}$

相关问题 更多 >