代码之家  ›  专栏  ›  技术社区  ›  Francis Cugler

Python:输出值不一致

  •  1
  • Francis Cugler  · 技术社区  · 6 年前

    我正在关注3Blue1Brown在Youtube上的在线视频: Youtube:3Blue1Brown

    现在,他使用的是Python v.3.7.0,我使用的是pythonv.3.7.4。我已经安装了Numpy,我的解释器已经集成到窗口的命令提示符中。我不是在创建一个真正的Python文件,我只是在Python的解释器中直接运行代码。

    这是程序和我的结果的整个命令提示符输出的副本。。。

    C:\Users\skilz99>python
    Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit
    (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import numpy as np
    >>> import math
    >>>
    >>> def get_primes(n_min, n_max):
    ...     result = []
    ...     for x in range(max(n_min, 2), n_max):
    ...         has_factor = False
    ...         for p in range(2, int(np.sqrt(x)) + 1):
    ...             if x % p == 0:
    ...                 has_factor = True
    ...                 break
    ...             if not has_factor:
    ...                 result.append(x)
    ...     return result
    ...
    >>> get_primes(0,50)
    [5, 7, 9, 11, 11, 13, 13, 15, 17, 17, 17, 19, 19, 19, 21, 23, 23, 23, 25, 25, 25
    , 27, 29, 29, 29, 29, 31, 31, 31, 31, 33, 35, 35, 35, 37, 37, 37, 37, 37, 39, 41
    , 41, 41, 41, 41, 43, 43, 43, 43, 43, 45, 47, 47, 47, 47, 47, 49, 49, 49, 49, 49
    ]
    >>>
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bernardo Duarte    6 年前

    我相信你要写的代码是:

    import numpy as np
    import math
    def get_primes(n_min, n_max):
        result = []
        for x in range(max(n_min, 2), n_max):
            has_factor = False
            for p in range(2, int(np.sqrt(x)) + 1):
                if x % p == 0:
                    has_factor = True
                    break
            if not has_factor:
                result.append(x)
        return result
    get_primes(0,50)
    

    问题是第二个if语句,它决定了 x 是否应附加到 result 列表。