简体   繁体   English

计算Python中的素数总和-此代码行起什么作用?

[英]Calculating the sum of primes in Python - what purpose does this line of code serve?

I have a short function that will calculate the sum of all prime numbers up to a limit. 我有一个简短的函数,它将计算所有素数的总和,直到一个极限。 Here is the full code for context: 这是上下文的完整代码:

def primes_sum(limit):
    limitn = limit+1
    not_prime = [False] * limitn
    primes = []

    for i in range(2, limitn):
        if not_prime[i]:
            continue
        for f in xrange(i*2, limitn, i):
            not_prime[f] = True

        primes.append(i)

    return sum(primes)

Most of this makes sense to me, but I don't understand this part: 这大部分对我来说很有意义,但我不明白这一部分:

not_prime = [False] * limitn

What exactly is the purpose of this? 目的到底是什么? How does it work and how does it find out whether or not a number is prime? 它是如何工作的以及如何确定数字是否为质数? I've tried looking it up, but I can't find the answer. 我尝试查找它,但找不到答案。

Thanks in advance. 提前致谢。

You are simply creating a list of length limitn with all it's element initialized to False . 您只是在创建一个长度限制listlimitn其所有元素初始化为False

* is a repetition operator. *是重复运算符。 When applied on a List with an integer value n as the right operand, it repeats the list n times. 当将一个integer数值n作为right操作数应用于List时,它将重复该list n次。

You can use it over strings also: 您还可以在字符串上使用它:

>>> [False] * 2
[False, False]
>>> "rohit" * 2
rohitrohit

It initializes a list of limitn False values. 它初始化一个limitn False值列表。 eg: 例如:

>>> [False]*3
[False, False, False]

Basically it prevents you from getting an IndexError later on. 基本上,它可以防止您以后出现IndexError

[False]*n initializes list with n elements which are all False. [False]*n使用全部为False的n个元素初始化列表。 That way of initialization is often used as a way of optimization when you know how much elements will list contain in advance - it's much faster than adding elements with .append(). 当您事先知道要列出的元素数量时,该初始化方法通常用作优化方法-比使用.append()添加元素快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM