Python 舍入整数

Python 舍入整数,python,list,Python,List,我有15个号码 [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000] 我有人输入数量,我希望它四舍五入到最低数量。因此,如果有人输入36,它将转到30对分将在O(日志N)中执行: 或者使用纯python和O(N): >>L=[1,5,10,20,30,50,70,100,150,200,500,1000,2000,5000,10000] >>>下一步(elem为elem,如果elem使用纯python:

我有15个号码

[1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]

我有人输入数量,我希望它四舍五入到最低数量。因此,如果有人输入
36
,它将转到
30

对分
将在O(日志N)中执行:

或者使用纯python和O(N):

>>L=[1,5,10,20,30,50,70,100,150,200,500,1000,2000,5000,10000]
>>>下一步(elem为elem,如果elem使用纯python:

>>> numbers = [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]
>>> x = 36
>>> max(n for n in numbers if n <= x)
30
>>数字=[1,5,10,20,30,50,70,100,150,200,500,1000,2000,5000,10000]
>>>x=36

>>>max(n表示n,如果n这里是一个递归解决方案。它应该是O(logn);它依赖于列表已排序的事实

L = [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]

def roundit(x,n):
    if len(x) == 1:
        return x[0]
    elif x[len(x)/2] > n:
        return roundit(x[0:len(x)/2],n)
    else:
        return roundit(x[len(x)/2 :],n)
结果:

>>> roundit(L,36)
30
>>> roundit(L,77)
70
>>> roundit(L,150)
150

+1,但不应调用变量
l
(8)需要注意的是,对分假设列表已排序,并且不能正确处理未排序的列表。如果您使用的是迭代器,为什么不
reversed
L
重命名,假定排序列表,迭代器reversed,感谢所有评论。感谢所有这一切,本网站太棒了!欢迎来到Stackoverflow社区。为了参与,最好包含您尝试过的代码,而不是询问解决方案。很多人会帮助您解决问题,但请他人为您提出解决方案是一种不好的做法。对不起,克里斯,谢谢你的提示,将来可以吗?是O(ln(n))?用x[0:len(x)/2]获得一半的账单需要记录(n),不是吗?@MatthieuW,
O(ln(n))
=
O(log(n))
,我只是称之为自然日志。@MatthieuW,好吧,我四处搜索,似乎没有使用“我的符号”;因此,我改成了标准符号。谢谢你指出。我的评论更多的是关于复制部分列表所花费的时间。如果你考虑到这一次,你就是O(n)
L = [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]

def roundit(x,n):
    if len(x) == 1:
        return x[0]
    elif x[len(x)/2] > n:
        return roundit(x[0:len(x)/2],n)
    else:
        return roundit(x[len(x)/2 :],n)
>>> roundit(L,36)
30
>>> roundit(L,77)
70
>>> roundit(L,150)
150