Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reduce the number of conditions in a statement? [duplicate]

In this exercise I need to come up with a way to find the least common multiple (LCM) for the first 20 natural numbers (1-20). So far this is what I got:

if exercise == 34:
    lcm = 20
    while lcm % 2 != 0 or \
            lcm % 3 != 0 or \
            lcm % 4 != 0 or \
            lcm % 5 != 0 or \
            lcm % 6 != 0 or \
            lcm % 7 != 0 or \
            lcm % 8 != 0 or \
            lcm % 9 != 0 or \
            lcm % 10 != 0 or \
            lcm % 11 != 0 or \
            lcm % 12 != 0 or \
            lcm % 13 != 0 or \
            lcm % 14 != 0 or \
            lcm % 15 != 0 or \
            lcm % 16 != 0 or \
            lcm % 17 != 0 or \
            lcm % 18 != 0 or \
            lcm % 19 != 0 or \
            lcm % 20 != 0:
        lcm += 1
    print(lcm)

Is there a more efficient, to code this without the need to write a condition for every potential number to be factored in the loop?

like image 346
Milky Avatar asked Aug 13 '20 04:08

Milky


People also ask

How do you reduce a condition in python?

Use If/Else Statements in One Line To simplify the code and reduce the number of lines in the conditional statements, you can use an inline if conditional statement. Consider the following concise code that performs the same with one line for each if/else conditional statement.

How many conditions can if statement handle?

Technically only 1 condition is evaluated inside an if , what is ascually happening is 1 condition gets evaluated and its result is evaluated with the next and so on... There is no defined limit to the length of a boolean expression; likely, you will run into memory problems at some point.


2 Answers

Here is a shorter version, replace long or with any

if excercise == 34:
    lcm = 20
    while any(lcm % i != 0 for i in range(2, 21)):
        lcm += 1
    print(lcm)
like image 132
sushanth Avatar answered Oct 23 '22 05:10

sushanth


I'd say best way will be this:

>>> math.lcm(*range(1, 21))
232792560

As the result is fairly large, your += 1 loop will take quite long no matter how nice others make it.

Best way before Python 3.9 might be something like this:

>>> def lcm(a, b):
        return a * b // math.gcd(a, b)

>>> functools.reduce(lcm, range(1, 21))
232792560

Both ways take only a few microseconds.

Or... with a little bit of head work, you could just multiply the largest powers of all primes in that range:

>>> 16*9*5*7*11*13*17*19
232792560
like image 6
superb rain Avatar answered Oct 23 '22 04:10

superb rain