简体   繁体   中英

how to find number that's divisible by a number in a given range?

I have this code:

generateMin = 150
generateMax = 250
if (current_level.world_shift * -1 % n == 0
        for n in range(generateMin, generateMax)):
    print("in range")

Which is checked at 100 FPS — as I move right/left current_level.world_shift is changed. However this code does not work. Can someone help me with that?

I think you're misunderstanding the range() method. It doesn't create a random number, it creates a list of numbers in a particular range. Eg, range(1,5) yields [1,2,3,4]

import random
generateMin = 150
generateMax = 250
if (current_level.world_shift * -1 % random.randint(generateMin, generateMax) == 0):
        print("in range")

I think you were trying to have an assignment in the conditional, eg, if (n == 1 with n = 1) , but mistakenly ended up using list comprehension, which always validated as True . I'm kind of amazed that didn't give a syntax error.

Python does not support assignment within a conditional, you'll need to assign before the if, or don't assign at all, like in the above code.

You can't use a generator expression in an if statement like that. This is because initially a generator expression yields a new generator object and instances of most types are generally considered True (see Truth Value Testing in the documentation).

To do what you want I suggest you instead use the built-in any() function. Doing so will be fast because it will stop soon as a True boolean sub-expression value is encountered.

Here's what I mean:

# a couple of things to allow dot syntax used in question to be used in answer
class Level: pass
current_level = Level()

current_level.world_shift = -175
generateMin = 150
generateMax = 250

if any(current_level.world_shift*-1 % n == 0
        for n in range(generateMin, generateMax)):
    print("in range")

any() will return True if current_level.world_shift*-1 is evenly divisible by any number in the open-ended range (assuming that's what you're trying to determine). By open-ended I mean that the value generateMax will not be considered because range(start, stop) only covers the values from start to stop-1 .

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