Condition in range function in python

Question:

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 ?

Asked By: Alex Nikitin

||

Answers:

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)
Answered By: MatsLindh

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)

Edit: I’ve been suggested the simpler syntax

for i in filter(lambda i: i % 11 == 0, range(101, 999)):
     print(i)
Answered By: Antonius

I came up without range

((y // k) - (x // k)) + 1 if x % k == 0 else (y // k) - (x // k)
Answered By: Alex Nikitin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.