はこちらitertoolsからpermutations
とcombinations_with_replacement
を使用して、単純な志向のアプローチです:それは発電機を使用して効率的に、より多くのスペースを作ることができる
[1, 3, 7, 9, 11, 13, 17, 19, ..., 9971, 9973, 9977, 9979, 9991, 9993, 9997, 9999]
from itertools import permutations, combinations_with_replacement
def digit_combinations(power_of_ten):
numbers = set()
for n in range(1, power_of_ten + 1):
for combination in combinations_with_replacement("1379", n):
numbers |= set(permutations(combination, len(combination)))
return sorted(int(''.join(number)) for number in numbers)
print(digit_combinations(4))
OUTPUTが、範囲に応じて、それは価値がないかもしれません。 (最大10,000までは340の数字しかありません)。10^4までの数値の場合、このコードは単純な例と同じくらい長くかかります。しかし、10^7の場合、このコードはあなたの単純な例よりも私のシステムで40倍速く走ります。
発電機のアイデアを含めることはできますか?
は、ここで上記発電フォームにコードの基本的なリワークです:
from itertools import permutations, combinations_with_replacement
def digit_combinations_generator(power_of_ten):
for n in range(1, power_of_ten + 1):
for combination in combinations_with_replacement("1379", n):
for number in set(permutations(combination, len(combination))):
yield int(''.join(number))
generator = digit_combinations_generator(4)
while True:
try:
print(next(generator), end=', ')
except StopIteration:
print()
break
これませないそれだけの速それはそれらを生成してそれらを渡し、ソートされた数値を返します。
優れています。私はたぶんこれを発電機にしていますが、以前はコンビネーションとの間に気づかなかったのです!ありがとうございました。 –
発電機のアイデアを含めることができますか? –
@ JohnnyApple、私はジェネレータバリアントを追加しましたが、それはすべての候補番号のリストを作成しないという点を除いて、私の元の機能よりも改善されているとは言えません。 – cdlane