简体   繁体   中英

Condition in range function in python

Is there any syntax in python to create range with condition? For example:

in range(101, 9999999999999999999999999999999999999999999)

count all numbers, divisible by 11 . Iterating over all range like

len([i for i in range(101, 9999999999999999999999999999999999999999999) if % 11 = 0]) is very slow. I tried to do vectorization filtering on numpy array

np.arange(101, 9999999999999999999999999999999999999999999, dtype=np.int8)

but numpy throws

Maximum allowed size exceeded

So my guess is to initially do not include do not dividable numbers in range. Is there any way to do it in range function?

Any number that is divisible by 11 would be starting at the first number after your starting index that can be divided by 11 (which should be quick to find: s_idx + 11 - s_idx % 11 should work), and then using the step parameter to range to move 11 each time.

range(start, end, 11)

For your specific example, you could just do

def range_mod(start, stop, mod):
    return range(start + start % mod, stop, mod)

print(len(range_mod(101, 9999, 11)))

But here is a more general example for a range function that iterates with arbitrary condition:

def range_with_condition(start, stop, func):
    for i in range(start, stop):
        if func(i):
            yield i

                                                                                                                                                                 
def mycondition(i):
    return i % 11 == 0


for i in range_with_condition(101, 999, mycondition):
    print(i)

I came up without range

((y // k) - (x // k)) + 1 if x % k == 0 else (y // k) - (x // k)

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