如何实现布尔值数组,由整数 2 到 n 索引



我不知道如何获取布尔值数组,由整数 2 到 n 索引。

我尝试了以下代码,它有效,但我认为它很愚蠢,一定有更好的东西。顺便说一句,我首先认为我不需要编写前两个插入调用,但在 python 中,即使我完全编写 insert(2, True(,python 也会只将 True 放在数组的第一个元素中,换句话说,a[0] = True 而不是 a[2] = True。

a = []
a.insert(0, 1)
a.insert(1, 1)
for index in range(2, n + 1):
    a.insert(index, True)

我正在寻找另一种简单而鼓舞人心的方法来实现它 [布尔值数组,由整数 2 到 n 索引]

编辑:我试图从 https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 编写伪代码,

Input: an integer n > 1.
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
    if A[i] is true:
        for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
           A[j] := false.
Output: all i such that A[i] is true.

如您所见,我只需要一个从索引 2 开始的列表。我知道怎么做这个算法,但我只是觉得我创建 [一个布尔值数组,由整数 2 到 n 索引] 的方式并不好。

Python 列表总是从零开始索引。如果要创建一个 True 从 2 到 N 的列表,可以创建如下内容:

N = 5
a = [None] * 2 + [True] * (N-2)

[None, None, True, True, True]

并在以后的代码中仅使用索引 2 或更多。

最新更新