プロジェクトオイラーの問題14は、多くの人がここで尋ねてきた特定のパズルについて説明しています。私の質問は、問題を解決する方法や他の人のエラーを修正する方法ではありません。パズルを考えた後、次の「解決策」が書かれましたが、間違っているようです。誰かが私のエラーを説明できますか?
def main():
# start has all candidate numbers; found has known sequence numbers
start, found = set(range(1, 1000000)), set()
# if are numbers in start, then there are still unfound candidates
while start:
# pick a random starting number to test in the sequence generator
number = start.pop()
# define the set of numbers that the generator created for study
result = set(sequence(number, found))
# remove them from the candidates since another number came first
start -= result
# record that these numbers are part of an already found sequence
found |= result
# whatever number was used last should yield the longest sequence
print(number)
def sequence(n, found):
# generate all numbers in the sequence defined by the problem
while True:
# since the first number begins the sequence, yield it back
yield n
# since 1 is the last sequence number, stop if we yielded it
if n == 1:
break
# generate the next number in the sequence with binary magic
n = 3 * n + 1 if n & 1 else n >> 1
# if the new number was already found, this sequence is done
if n in found:
break
if __name__ == '__main__':
main()
ドキュメントは後で追加され、うまくいけば、それが機能すると思った理由を説明するのに十分明確です。