小编Dan*_*ny 的帖子

在 Python 中检查数字是否是列表中的质数

我写了下面的代码,它应该检查列表中的数字是否是质数,但是有一个我无法解决的问题,因为我正在尝试实现对平方根的检查优化num,我有一个类型错误。

def is_prime(x):
    if x <= 1:
        return False
    if x == 2:
        return True
    for n in range(3, x**(0.5)+1, 2):   # this skips even numbers and only checks up to sqrt(x)
        if x % n == 0:
            return False
    return True


my_list = [1,2,4,5,6,7]
result = list(map(is_prime,my_list))

print(result)
Run Code Online (Sandbox Code Playgroud)
  File "PrimeCheck.py", line 39, in <module>
    result = list(map(is_prime,my_list))
  File "PrimeCheck.py", line 32, in is_prime
    for n in range(3, x**(0.5)+1, 2):   # this skips even numbers and only checks up to …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

0
推荐指数
1
解决办法
3152
查看次数

在python中理解while循环

我是Python的新手,并试图学习算法,我想问一下,为什么low < hi在查看列表时使用它是逻辑错误,正确的逻辑操作是low <= hi什么,它阻止的边缘情况.

def binary_search(input_array, value):
    """Your code goes here."""
    #O(log(n))
    low = 0
    hi = len(input_array) - 1 
    while low <= hi: #why cant it be low < hi
        mid = (low + hi)//2
        if input_array[mid] == value:
            return mid
        elif input_array[mid] < value:
            print(low, hi)
            low = mid + 1
        else:
            hi = mid - 1
    return -1


test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print(binary_search(test_list, test_val1))
print(binary_search(test_list, …
Run Code Online (Sandbox Code Playgroud)

python data-structures python-3.x

0
推荐指数
1
解决办法
67
查看次数

标签 统计

python ×2

python-3.x ×2

data-structures ×1