简体   繁体   中英

Using Operators with randint()

I'd like to implement a function where a value is incrementally increased with randint() between x and x * 1.1 BUT I'd like to cap the range when it's been used enough times.

Is it possible to combine something like 'and' with the properties of randint(). I've fooled around for a while but haven't come up with something that works. Maybe I'm missing something obvious re: syntax.

eg new_val = randint(old_val, (old_val * 1.1) and !> max_val)

This seems like a nice place to use a generator:

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

then

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

gives something like

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

In the end I managed to find a novel workaround. I wanted the flexibility to call the function recursively so I used min() instead of a generator.

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))

It's harder to read than I would like but seems to be working!

Use 'min'?..

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

or if this is what you want..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM