对于ProjectEuler上的任务,我编写了一些代码,该代码使用强力来查找低于100的最长的素数链,这些素数加起来为素数,并且代码确实给出了正确的结果。 因此对于低于100的数字,答案是2 + 3 + 5 + 7 + 11 + 13 = 41
import math def prime(n): for x in xrange(2,int(math.sqrt(n)+1)): if n%x == 0: return False return True primes = [] for x in xrange(2,100): if prime(x): primes += [x] record = 0 i = 0 for num in primes: i += 1 chain = [num] for secnum in xrange(i,len(primes)-1): chain += [primes[secnum]] if len(chain) > record and sum(chain) in primes: record = len(chain) seq = chain print seq print seq当我运行此代码时,我得到了
[2, 3] [2, 3, 5, 7] [2, 3, 5, 7, 11, 13] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89]最后一行对我来说非常困惑。 在我看来,两个印刷语句应该给出相同的结果。 我的变量seq是如何分配给那个长列表的? 最后一个列表甚至不满足分配了seq的if语句的要求。 我确定这是一些非常愚蠢的脑屁,但我无法弄清楚我搞砸了什么
For a task on ProjectEuler I've written code that uses brute force to find the longest chain of primes below 100 that add up to a prime, and the code does give the correct results. So for numbers below 100 the answer is 2 + 3 + 5 + 7 + 11 + 13 = 41
import math def prime(n): for x in xrange(2,int(math.sqrt(n)+1)): if n%x == 0: return False return True primes = [] for x in xrange(2,100): if prime(x): primes += [x] record = 0 i = 0 for num in primes: i += 1 chain = [num] for secnum in xrange(i,len(primes)-1): chain += [primes[secnum]] if len(chain) > record and sum(chain) in primes: record = len(chain) seq = chain print seq print seqWhen I run this code I get
[2, 3] [2, 3, 5, 7] [2, 3, 5, 7, 11, 13] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89]That last line is extremely confusing to me. In my mind the two print statements should give the same reult. How did my variable seq get assigned to that long list? The last list doesn't even meet the requirements of the if statement wherein seq is assigned. I'm sure this is some really silly brain fart, but I just can't figure out what I screwed up
最满意答案
seq = chain创建对同一chain列表的另一个引用 。 然后打印该列表,但循环不会停止 。
你继续扩展chain ,并且因为seq只是对该列表的引用,所以一旦循环结束,你将看到这些变化。 在剩余的for循环迭代期间, chain / seq继续更改,但if条件不再满足,因此您不会看到这些更改发生。
你继续在这里扩展chain :
chain += [primes[secnum]]这使用增强赋值 ; 它不会创建新列表,而是扩展现有列表。 它相当于chain.extend(primes[secnum]) 。
您可以通过创建要在seq存储的chain 副本来解决此问题:
seq = chain[:]seq = chain creates another reference to the same chain list. You then print that list, but the loop doesn't stop.
You continue to expand chain, and since seq is just a reference to that list, you'll see those changes once the loop has ended. During the remaining for loop iterations chain / seq continues to change, but the if condition is no longer met so you don't see these changes take place.
You continue to expand chain here:
chain += [primes[secnum]]This uses augmented assignment; it doesn't create a new list but extends the existing list. It is equivalent to chain.extend(primes[secnum]).
You can fix this by creating a copy of chain to store in seq:
seq = chain[:]更多推荐
发布评论