代码之家  ›  专栏  ›  技术社区  ›  juangalicia

最主要的问题是:这部分代码在做什么?next(x表示count(0)中的x,如果isPrime(s+x))

  •  0
  • juangalicia  · 技术社区  · 2 年前

    我正在检查一个代码战争卡塔的解决方案,它与获得最接近的素数有关。这是卡塔的链接以获取更多信息。 Transform to Prime

    但我不理解一位用户的解决方案,他做了这个:

    from itertools import count
    
    def isPrime(n):
        return n == 2 or n%2 and all(n%x for x in range(3,int(n**.5)+1,2))
    
    def minimum_number(numbers):
        s = sum(numbers)
        return next(x for x in count(0) if isPrime(s+x))
    

    功能是什么 next(x for x in count(0) if isPrime(s+x)) ?因为 count(0) 对我来说没有意义。

    2 回复  |  直到 2 年前
        1
  •  3
  •   Alain T.    2 年前

    count(0) 是一个无限序列生成器,对手头的问题来说是一种过度处理。基于 Bertrand's postulate (已经证明) s 2*s ,因此该函数可以使用一个简单的范围:

    def minimum_number(numbers):
        s = sum(numbers)
        return next(x for x in range(s) if isPrime(s+x))
    
        2
  •  1
  •   Michael M.    2 年前

    第一 count(0) 只返回一个起始于的无限迭代器 0 并且从未停止(即: 0 , 1 , 2 , 3 , 4 ,永远持续下去)。

    然后用户使用 x for x in count(0) if isPrime(s+x) 要围绕这个无限迭代器创建生成器,请使用 generator expression .生成器表达式的语法非常直接:对于每个输出 x 从…起 计数(0) 这使得 isPrime(s+x) true,输出 x 。基本上,原件 count() 迭代器被过滤为仅满足条件的输出 isPrime(s+x)

    最后,用户使用 next() 函数,该函数获取该生成器的下一个输出。因为生成器是从生成器表达式中新创建的,所以这只是生成器生成的第一个数字。或者,的第一个非负整数值 x 这使得 isPrime(s+x) 回来 True

        3
  •  1
  •   nate-thegrate    2 年前
    return next(x for x in count(0) if condition)
    

    count(0) 是一个可迭代的,它给出了 int s(即0、1、2、3、4、5)

    next() 给出迭代中的下一个值。调用一次会得到第一个值。

    因此,上面的语句将返回该序列中满足条件的第一个数字。下面是另一种写法:

    x = 0
    while not condition:
        x += 1
    return x