あなたは統合if
にして、リストの内包表記を使用することができます:あなたは、ループの最初に一度行うことで、各番号のモジュロを再計算し、身体の残りの部分で結果を使用して回避することができます除数のリストを取得します。それが空なら、あなたは"This is not a multiple of ..."
この方法で印刷することができ、それが可能な除数を追加し、その結果を説明文を書くために簡単です:
N = 30
primes = [3, 5]
primes_str = ' or '.join(str(p) for p in primes)
for n in range(1, N + 1):
divisors = [str(p) for p in primes if n % p == 0]
if divisors:
print("%d is a multiple of %s." % (n, ' and '.join(divisors)))
else:
print("%d is not a multiple of %s." % (n, primes_str))
それは出力:
1 is not a multiple of 3 or 5.
2 is not a multiple of 3 or 5.
3 is a multiple of 3.
4 is not a multiple of 3 or 5.
5 is a multiple of 5.
6 is a multiple of 3.
7 is not a multiple of 3 or 5.
8 is not a multiple of 3 or 5.
9 is a multiple of 3.
10 is a multiple of 5.
11 is not a multiple of 3 or 5.
12 is a multiple of 3.
13 is not a multiple of 3 or 5.
14 is not a multiple of 3 or 5.
15 is a multiple of 3 and 5.
16 is not a multiple of 3 or 5.
17 is not a multiple of 3 or 5.
18 is a multiple of 3.
19 is not a multiple of 3 or 5.
20 is a multiple of 5.
21 is a multiple of 3.
22 is not a multiple of 3 or 5.
23 is not a multiple of 3 or 5.
24 is a multiple of 3.
25 is a multiple of 5.
26 is not a multiple of 3 or 5.
27 is a multiple of 3.
28 is not a multiple of 3 or 5.
29 is not a multiple of 3 or 5.
30 is a multiple of 3 and 5.
をあなただけならば数値が倍数でない場合は、any
またはall
を使用してテストします。
for n in range(1, N + 1):
if all(n % p for p in primes):
print("%d is not a multiple of %s." % (n, primes_str))
for n in range(1, N + 1):
if not any(n % p == 0 for p in primes):
print("%d is not a multiple of %s." % (n, primes_str))
7と11を考慮する場合は、primes = [3, 5, 7, 11]
と定義してください。
'%a3と%5:'ならば? –