如何更改使用xrange在python 3中运行的代码?

我正在阅读O'Reilly集合中的高性能Python书,在第11页中,我发现此代码适用于python 2,这里的要点是使一条指令可以同时执行多个指令(通过向量化)

import math 
def check_prime(number):
    sqrt_number = math.sqrt(number)
    number_float = float(number)
    numbers = range(2, int(sqrt_number)+1)
    for i in xrange(0, len(numbers), 5):
          # the following line is not valid Python code
          result = (number_float / numbers[i:(i+5)]).is_integer()
          if any(result):
                 return False
    return True

但是我得到这个错误

TypeError: unsupported operand type(s) for /: 'float' and 'list'

我试图将其更改为可在python 3上工作,这是我的尝试:

import math

def check_prime(number):
    sqrt_number = math.sqrt(number)
    number_float = float(number)
    numbers = list(range(2, int(sqrt_number)+1))

    for i in range(0, len(numbers), 5):
        # the following line is not valid Python code
        result = (number_float / numbers[i:(i+5)]).is_integer()
        if any(result):
            return False
    return True

I changed the xrange for range and the range(2, int(sqrt_number)+1) for list(range(2, int(sqrt_number)+1)) but i did not have succeed in this. I suppose there is a special operator for sets or something like that but have no idea. if any of you people can help me I'll be so grateful whit you

评论
  • xeos
    xeos 回复

    尝试这个:

    import math
    
    def check_prime(number):
        sqrt_number = math.sqrt(number)
        number_float = float(number)
        numbers = list(range(2, int(sqrt_number)+1))
    
        for i in range(0, len(numbers), 5):
            result = [number_float % num == 0 for num in numbers[i:(i+5)]]
            if any(result):
                return False
        return True
    
  • 回忆那么真
    回忆那么真 回复

    I looked at the book and that line is not supposed to actually work as is; you cannot divide by a list in Python. The author uses that code as an example of what vectorization would look like. The # the following line is not valid Python code comment is in the original to indicate that.

    就功能和语义而言,最接近的可能是以下代码:

    import math
    
    def check_prime(number):
        sqrt_number = math.sqrt(number)
        number_float = float(number)
        numbers = list(range(2, int(sqrt_number)+1))
    
        for i in range(0, len(numbers), 5):
            # the following line is now valid Python code, but not vectorized
            result = [(number_float / n).is_integer for n in numbers[i:(i+5)]]
            if any(result):
                return False
        return True
    

    Note that the processing for result in this version is not done in parallel, so it's probably not what the author wanted to demonstrate. As far as I know, vectorization isn't natively available in Python, you would have to use numpy to do it. This article should be useful if you want to try it.