使用python代码计算有多少整数严格大于其右边的所有整数

2024-10-03 02:47:28 发布

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

给定整数列表,X, https://www.google.com/url?q=https://docs.google.com/document/d/1TjeNYpZ_PbdBISlJPF-_WqULBc1WpuYthLClovjB3Rs/edit?usp%3Dsharing&sa=D&ust=1594968749928000&usg=AFQjCNG8bAv1lX8pXr4CYcgaDfYFxcbgCg

我想写代码来计算有多少个整数严格大于其右边的所有整数,不包括最后一个数字,因为它的右边没有数字。例如,[2,3,1]的答案应该是1,而[12,4,4,2,2,3]的答案是2。我不知道如何写代码。我将非常感谢任何关于如何进行的指导


Tags: 答案代码httpscomurldocs列表www
3条回答

这个代码怎么样

mylist = list(map(int,input().split()))
count = 0

for i,item in enumerate(mylist): 
    if i == len(mylist) - 1: #here we excluded the last element for a check
        break

    check = max(mylist[i+1:])
    if check < item:
        count = count + 1    

print(count)

我从两个方面低估了这个问题:

    counter = 0
    for i in range(len(list_of_number)):
        for j in range(i, len(list_of_number)):
           if list_of_number[j] > list_of_number[i]:
               counter += 1

在这里,在获得第一个值后,它扫描所有列表。它后面的代码将只检查号码的右邻居

    counter = 0
    for i in range(len(list_of_number)-1):
        if list_of_numbers[i+1] > list_of_numbers[i]:
            counter +=1

这里有一个在O(N)中实现这一点的解决方案,其中N是列表的大小

l = [12,4,4,2,2,3]

def max_so_far(l):
    m = 0
    for i in l[::-1]: 
        m = max(m, i)
        yield m

sum([x>y for x,y in zip(l[-2::-1], max_so_far(l))])

相关问题 更多 >