2016-10-17 2 views
-2

Existe-t-il un moyen plus idiomatique d'accomplir ce qui suit dans Python3?Il doit y avoir un meilleur moyen

if i%1 == 0 and i%2 == 0 and i%3 == 0 and i%4 == 0 and i%5 == 0 and i%6 == 0 and i%7 == 0 and i%8 == 0 and i%9 == 0 and i%10 == 0 and i%11 == 0 and i%12 == 0 and i%13 == 0 and i%14 == 0 and i%15 == 0 and i%16 == 0 and i%17 == 0 and i%18 == 0 and i%19 == 0 and i%20 == 0: 

Je suis en train de trouver le plus petit nombre positif qui est divisible par tous les nombres de 1 à 20. Je ne suis pas à la recherche d'une nouvelle solution. Je cherche une manière plus claire d'exprimer ce que je fais ci-dessus.

+0

Essayez d'utiliser une boucle 'for'. Aussi, veuillez formater votre code. – Bim

Répondre

6

Oui utiliser all avec range:

if all(i % j == 0 for j in range(1, 21)): # python2 -> xrange(2, 21) 
    # do whatever 

Si tous i % j == 0, il retournera Vrai sinon il court-circuit et retour Faux s'il y a un reste pour i % j. En outre, la vérification if i % 1 est redondante afin que vous puissiez commencer à 2.

Ou conversly, vérifier s'il n'y a pas anyi % j avec un reste.

if not any(i % j for j in range(2, 21)): 

Ou si vous préférez fonctionnelle:

if not any(map(i.__mod__, range(2, 21))) 
+1

Ou sur Py2, pour des avantages de perf doux, 'xrange'. Pas un gros problème non plus, étant donné que la gamme est petite. – ShadowRanger

+0

@ShadowRanger, vrai, a ajouté un commentaire. –

0

Vous pouvez utiliser la fonction all combinée à une compréhension de la liste - ou mieux encore - une expression du générateur:

if all(i%(1 + j) == 0 for j in range(20)): 
0

Utilisation une boucle for dans une boucle while.

num = 1; 
while(True): #keeps going until it finds the number 
    b = True #remains true as long as it is divisible by div 
    for div in range(1,21): 
     if not (num % div == 0): 
      b = False #number was not divisible, therefore b is now false 
      num += 1 
      break 
    if(b): #b means num was divisible by all numbers. 
     break 
print(num)