如何有效地检查python中的连续范围 [英] how to efficiently check contiguous ranges in python

查看:46
本文介绍了如何有效地检查python中的连续范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据范围分配成绩:

def getGrade(size):等级=''如果大小 <= 32:等级 = 'p4'elif 大小 >32 和大小 <=64:等级 = 'p6'elif 大小 >64 和大小 <= 128:等级 = 'p10'elif 大小 >128 和大小 <= 256:等级 = 'p15'elif 大小 >256 和大小 <=512:等级 = 'p20'elif 大小 >512 和大小 <= 1024:等级 = 'p30'elif 大小 >1024 和大小 <= 2048:等级 = 'p40'......

问题是需要再添加 20 个检查,所以有没有比这种方法做得更好的方法.

解决方案

由于范围连续,可以避免重复下界.

将所有范围放在元组中可以节省一些输入(如果第一个范围没有下降到负无穷大,请考虑在所有其他范围之前添加元组 (0, None) :

def getGrade(size):成绩=((32, 'p4'),(64, 'p6'),(128, 'p10'),...)对于 maxVal,成绩等级:如果大小 <= maxVal:返回等级

测试:

<预><代码>>>>获得等级(45)'p6'>>>获得等级(100)'p10'

效率:

如果 grades 列表真的很长,您可以获得比扫描每个项目更好的运行时间.由于列表已排序,您可以使用 bisect,通过替换 for 循环:

 为 maxVal,成绩等级:如果大小 <= maxVal:返回等级

与:

 index = bisect.bisect(grades, (size, ))如果索引

步数减少(在最坏情况下)从 N(grades 的长度)减少到 log2(N).

assigning grade on basis of range:

def getGrade(size):
    grade =''
    if size <= 32:
        grade = 'p4'
    elif size > 32 and size <=64:
        grade = 'p6'
    elif size > 64 and size <= 128:
        grade = 'p10'
    elif size > 128 and size <= 256:
        grade = 'p15'
    elif size > 256 and size <=512:
        grade = 'p20'
    elif size > 512 and size <= 1024:
        grade = 'p30'
    elif size > 1024 and size <= 2048:
        grade = 'p40'
    ......

Problem is need to add 20 more check so is there any way to do better than this approach.

解决方案

Due do the ranges being contiguous, you can avoid repeating the lower bound.

Putting all the ranges in tuples can save you some typing (if the first range does not go down to negative infinity, consider adding the tuple (0, None) before all others:

def getGrade(size):
    grades = (
         (32, 'p4'),
         (64, 'p6'),
        (128, 'p10'),
        ...
    )

    for maxVal, grade in grades:
        if size <= maxVal:
            return grade

Test:

>>> getGrade(45)
'p6'
>>> getGrade(100)
'p10'

Efficiency:

If the grades list is really long, you can achieve better runtime than scanning every item. Since the list is sorted, you can use bisect, by replacing the for loop:

    for maxVal, grade in grades:
        if size <= maxVal:
            return grade

with:

    index = bisect.bisect(grades, (size, ))
    if index < len(grades):
        return grades[index][1]

The number of steps is reduced (in the worst case) from N (the length of grades) to log2(N).

这篇关于如何有效地检查python中的连续范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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