2017-02-27 74 views
0

我想实现一个函数,其中值随着x和x *之间的randint()递增而增加* 1.1但是我想在使用足够的时间时限制范围。使用运算符randint()

是否可以将'and'与randint()的属性结合起来。我已经愚弄了一段时间,但没有拿出一些有用的东西。也许我错过了显而易见的东西:语法。

如new_val = randint(old_val,(old_val * 1.1)和!> MAX_VAL)

+0

为什么你不能使用if语句? – abccd

+0

这是在'for'循环中吗?在这种情况下,为什么不能每次乘以1.1,而是调用'randint(int(old_val),int(old_val * 1.1))'? – roganjosh

+0

这可能有所帮助:http://stackoverflow.com/questions/1301735/counting-python-method-calls-within-another-method – Jacquot

回答

-1

用 '分'?..

new_val = randint(min(old_val,max_val),int(min(old_val*1.1,max_val))) 

,或者如果这是你想要的..

new_val = randint(old_val,int(old_val*1.1)) if old_val<max_val else None 
+1

'random.randint(old_val,old_val * 1.1)'是一个'ValueError'。你不能用'float'参数调用'randint'。 – roganjosh

0

这似乎是一个不错的地方使用发电机:

def capped_geometric_series(x, max_val, growth_factor=1.1): 
    while True: 
     x = randint(x, int(x * growth_factor)) 
     if x < max_val: 
      yield x 
     else: 
      break 

然后

for x in capped_geometric_series(30, 100): 
    print(x) 

给出类似

33 
36 
38 
40 
42 
46 
48 # Note: this allows the same value to be returned 
48 # multiple times; in fact, if x is too small 
48 # (ie if x * growth_factor < x + 1) 
52 # it will return x an infinite number of times. 
56 
59 
64 
67 
67 
68 
69 
73 
80 
82 
84 
84 
86 
91 
98 
98 
0

在我设法找到一个解决方法新颖结束。我想灵活地递归调用函数,所以我使用min()而不是生成器。

def function(val): 
    max_val = 100 
    old_val = (min(value,(int(max_aero * 0.9)) 
    new_val = random.randint(old_val, min(int(val* 1.1), max_val)) 

它比我想要更难阅读,但似乎工作!