Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elegant way of using a range using an if statement?

Tags:

python

I've got this very crude way of writing this IF statement .

for a in range (2,3000):
    if ( a % 1) == 0 and ( a % 2) == 0 and ( a % 3) == 0 and ( a % 4) == 0 and ( a % 5) == 0 and ( a % 6) == 0 and ( a % 7) == 0 and ( a % 8) == 0  and ( a % 9) == 0 and ( a % 10) == 0 :
    print a

I assume there is a much better way to write this, using for example a range function combined with the IF statement ?

like image 939
Finger twist Avatar asked Jun 06 '11 06:06

Finger twist


People also ask

Can range be used in if?

To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range. You can also check the other way around using not to the existing syntax.

What is a nested IF statement in Python?

You can have if statements inside if statements, this is called nested if statements.

How many nested if statements can an if statement contain in Python?

Python Nested if statements This is called nesting in computer programming. Any number of these statements can be nested inside one another.


2 Answers

For a more-or-less direct translation, how about

for a in range(2, 3000):
    if all(a % k == 0 for k in range(1,11)):
        print a

although of course a % 1 == 0 for all integers a, so that check is unnecessary.

like image 135
DSM Avatar answered Oct 12 '22 15:10

DSM


What you need is the multiples of LCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) which fall within your range. There's multiple ways of computing LCM (see. http://en.wikipedia.org/wiki/Least_common_multiple)

Since LCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) = 2^3 * 3^2 * 5 * 7 = 2520, you can do something like

lcm = 2520
i = 2/lcm
j = 3000/lcm
for k in range(i, j)
  print (k + 1) * lcm
like image 25
Matei Gruber Avatar answered Oct 12 '22 15:10

Matei Gruber