English 中文(简体)
甲型肝脏病
原标题:Python Syntax Problem

我只是回到了Euler项目,失去了我的账户和解决办法,因此我回头谈谈问题7。 然而,我的法典没有工作。 对我来说,这似乎相当少,有人能够帮助我解说我的(ort)文字?

应当找到1 0001名总理。

#!/usr/bin/env python
#encoding: utf-8
"""
P7.py

Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __ME__. All rights reserved.
"""

import sys
import os
from math import sqrt

def isPrime(num):
    flag = True
    for x in range(2,int(sqrt(num))):
        if( num % x == 0 ):
            flag = False
    if flag == True:
         return True
    else:
         return False

def main():
    i, n = 1, 3
    p = False
    end = 6
    while end - i >= 0:
        p = isPrime(n)
        if p == True:
            i = i + 1
            print n
        n = n + 1

if __name__ ==  __main__ :
    main()

Edit*:Sorry, 问题说的是每个数字都是主要问题:

最佳回答

syntax是罚款(第2条)。 异构体有某些可避免的并发症,这种非一次性的包裹:

for x in range(2,int(sqrt(num))):
    if( num % x == 0 ):
        flag = False

range(2,Y),从2个列入到Y,其中不包括<>/strong>,因此,你往往不核对最后可能的分歧,因此认为“primes”有许多是t。 作为最简单的固定装置,在<代码>-range上尝试了<1> + int(......。 之后,消除这些可避免的并发症是可取的:例如,

if somebool: return True
else: return False

由于更简单的<代码>回到了某些bool/code>,因此永远没有必要。

举例来说,你整个法典的简化版本(只有不可或缺的优化,但完全是相同的算法)可能是:

from math import sqrt

def isPrime(num):
    for x in range(3, int(1 + sqrt(num)), 2):
        if num % x == 0: return False
    return True

def main():
    i, n = 0, 3
    end = 6
    while i < end:
        if isPrime(n):
            i += 1
            print n
        n += 2

if __name__ ==  __main__ :
    main()

“一旦你知道答案”已经解释过,我就增加了一个更为关键的优化(+=2,而不是n<>t>/code>,因为我们的“知识”甚至数字“;3个不是主要内容;3个是“<>range<>>/code>的斜线”。

有可能找到切割者,例如:

def isPrime(num):
    return all(num % x for x n range(3, int(1 + sqrt(num)), 2))

虽然如果你不熟悉<<>all的编码>,这也许不会看上去“simpler”,但事实上,这是为了节省了你的工作(和读法者必须遵循的)低水平逻辑,有利于适当程度的抽象,表达功能的关键思想,即“当司被审理时,核心是所有可能的奇分辨者......”(即直接以精确和可执行的形式表述这一概念)。 内部算法实际上仍然相同。

进一步......:

import itertools as it

def odd():
    for n in it.count(1):
        yield n + n + 1

def main():
    end = 5        
    for i, n in enumerate(it.ifilter(isPrime, odd())):
        print n
        if i >= end: break

同样,这只是与以往一样的算法,在更为适当的抽象程度上刚刚表述:将奇数的顺序(从3个包括上层)引入自己的<代码>(奇生成者,以及在一定程度上使用<代码>(数字内和itertools)以避免不适当(和不必要的)低级表述/推理功能。

我再说一遍:尚未适用基本优化——只是适当的抽象。 在其他地方,例如。 (可能也要检查评论!) 这里,我着重说明(如果包含诸如<编码>数字、allany、重要<代码>itertools、加上发电机和发电机表示),在现代螺旋式螺旋式螺旋中,与“C-insed”相比,许多“电离”问题可在较适当的抽象程度在现代螺旋式螺旋式螺旋式螺旋式中表达,而“C-insed”则可能最自然地出现在以C方案拟订方式重新组合的多数方案设计者身上。 (C++使用先由Steanov确定的“强烈惩罚”的学者可能会令人惊讶地看到,Adhury通常会具有“举动溢价”,特别是如果“itertools<>因其bla升速度而广为人知,则广泛而适当地使用......但实际上这是一个不同的主题;-)

问题回答

这是否更好?

def isPrime(num):
    for x in range(2,int(sqrt(num))):
        if( num % x == 0 ):
            return False
    return True

而且:

def main():
    i, n = 1, 3
    while i <= 6:
        if isPrime(n):
            i = i + 1
            print n
        n = n + 1

另外,在座任何地方都看不到10001





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...