使用python来计算有多少个整数严格比其右边的所有整数大的代码 [英] Code to count how many integers are strictly larger than all the integers to their right using python

查看:42
本文介绍了使用python来计算有多少个整数严格比其右边的所有整数大的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出整数X的列表,
整数严格地比除最后一位数字外的所有其右边的整数都大,因为它的右边没有数字。例如。对于[2,3,1]的答案应该为1,而对于[12,4,4,2,2,3,3]的答案应该为2。我不知道如何编写代码。我将不胜感激任何有关如何进行操作的指南。

以下是在O(N)中执行此操作的解决方案,其中N是列表的大小。

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

def max_so_far(l):
m = 0
对于i in l [::-1]:
m = max(m,i)
收益m

sum([x中y的x,y的y(x [l:-2 ::-1],max_so_far(l))]))


Given the list of integers, 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

I want to write code to count how many integers are strictly larger than all the integers to their right excluding the last digit since it doesn’t have a number to its right. E.g. for [2,3,1] the answer should be 1 while for [12,4,4,2,2,3] the answer is 2. I have no clue how to write the code. I will appreciate any guidance on how to proceed.

解决方案

Here's a solution that does that in O(N), where N is the size of the list.

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))])

这篇关于使用python来计算有多少个整数严格比其右边的所有整数大的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆