Python:检测变量何时超过阈值间隔

时间:2015-04-23 13:40:10

标签: python

我正在寻找每次我的计数器达到(缺少更好的短语)阈值间隔时打印消息的方法。按阈值间隔,我的意思是例如每百万。 E.g:

value exceeds 1 million # Value == 1000001
value exceeds 2 million # Value == 2000014
value exceeds 3 million # Value == 3492090

我想过使用这样的东西:

if value % 10**6 == 0:
    print "Message"

但除非价值是百万美元,否则它不会起作用,例如:它不会检测新值是否为2000001。

有什么想法吗?

5 个答案:

答案 0 :(得分:2)

Alter Table table_name add OldCode int not null DEFAULT(0);

答案 1 :(得分:2)

只需跟踪超过百万的数量,每次增加一百万的目标。 (这假设你一次不会增加超过50万)

counter = 0
nextMillion = 1000000
if counter > nextMillion:
    nextMillion += 1000000
    # Print your message about the counter here.

答案 2 :(得分:1)

threshold = 10 ** 6
reached = 0

while True:
    _tmp = int(value/threshold)
    if _tmp > reached:
        reached = _tmp
        print "Value reached {}.".format(reached * threshold)

答案 3 :(得分:1)

我必须过于注重单行解决方案,才能看到简单的方法:

select
  *
from
  actors a

  inner join film_actor_director_genre fadg on 
    on fadg.aid = a.aid

  inner join film f on
    f.fid = fadg.fid

  -- This should return all actors that have been in 
  -- at lead 5 movies with a director. Note the count
  -- ordering and limit
  inner join (
    select top 5
      a.aid
    from
      film_actor_director_genre
    group by
      a.aid,
      d.did
    having
      count(*) >= 5
    order by
      count(*)
  ) t1 on
    t1.aid = a.aid

谢谢你们!

答案 4 :(得分:0)

对于这样一个小任务,可变性不大,所以让我们一路优化资源:

threshold = 10**6
next_limit = 1 * threshold

def check(value):
    global next_limit

    if value > next_limit:
        next_limit = value // threshold
        print "Value next_limit {} million.".format(next_limit)

在杰罗姆的帖子中,val已更改但不应更改。与Jamie的代码相比,这里将使用针对常见情况的最少操作(将限制检查为False)以及如果检查成功则使用较少的操作。