对变量赋值感到困惑(Python) [英] Confused about a variable assignment (Python)

查看:82
本文介绍了对变量赋值感到困惑(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于ProjectEuler上的一项任务,我编写了代码,该代码使用蛮力查找了小于100的最长素数链,这些素数加起来等于一个素数,并且该代码确实给出了正确的结果。因此,对于低于100的数字,答案是2 + 3 + 5 + 7 + 11 + 13 = 41

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 seq

运行此代码时,我会得到

When 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]

最后一行对我来说非常混乱。在我看来,这两个打印语句应给出相同的结果。我的变量seq如何分配给该长列表?最后一个列表甚至不符合其中分配了seq的if语句的要求。我敢肯定这真是个愚蠢的脑子屁,但我只是想不通自己搞砸了

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 =链创建另一个引用到同一列表。然后,您打印该列表,但循环不会停止

seq = chain creates another reference to the same chain list. You then print that list, but the loop doesn't stop.

您继续扩展链条,并且由于 seq 只是对该列表的引用,因此在循环结束后您将看到这些更改。在$ 循环的其余循环中, / seq 继续更改,但是 if 条件不再满足,因此您看不到这些更改发生。

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.

您继续在此处扩展 chain

chain += [primes[secnum]]

这使用 增补作业 ;它不会创建新列表,但会扩展现有列表。等效于 chain.extend(primes [secnum])

您可以通过创建<将的em> copy 存储在 seq 中:

You can fix this by creating a copy of chain to store in seq:

seq = chain[:]

这篇关于对变量赋值感到困惑(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆