2017-02-27 30 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)) 

它比我想要更難閱讀,但似乎工作!