Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何提高python代码的速度?_Python_Performance_Python 2.7_Python 3.x - Fatal编程技术网

如何提高python代码的速度?

如何提高python代码的速度?,python,performance,python-2.7,python-3.x,Python,Performance,Python 2.7,Python 3.x,所以我最近把它编码为一个小挑战,看看我能多快完成它。现在,由于它的工作,这样我想加快它。它可以找到一个数的所有适当的除法器,最高的适当除法器,以及它所需要的时间。问题是像5000这样的数字需要0.05秒,而像999999999这样的数字需要1567.98秒 这是旧代码,我在下面制作了一个新的改进版本 导入时间 def clearfile(name): file = open(name + ".txt", "r") filedata = file.read() file.c

所以我最近把它编码为一个小挑战,看看我能多快完成它。现在,由于它的工作,这样我想加快它。它可以找到一个数的所有适当的除法器,最高的适当除法器,以及它所需要的时间。问题是像5000这样的数字需要0.05秒,而像999999999这样的数字需要1567.98秒

这是旧代码,我在下面制作了一个新的改进版本

导入时间

def clearfile(name):
    file = open(name + ".txt", "r")
    filedata = file.read()
    file.close()
    text_file = open(name + ".txt", "w")
    text_file.write("")
    text_file.close()

def start():
    num = input("Enter your Number: ")
    check(num)

def check(num):
    try:
        intnum = int(num)
    except ValueError:
        error(error = "NON VALID NUMBER")
    if(intnum < 0):
        error(error = "POSITIVE NUMBERS ONLY")
    else:
        finddivisor(intnum)

def finddivisor(intnum):
    starttimer = time.time()
    i = 1
    print("\nThe divisors of your number are:"),
    while i <= intnum:
        if (intnum % i) == 0:
            print(i)
            file = open("numbers.txt", "r")
            filedata = file.read()
            file.close()
            text_file = open("numbers.txt", "w")
            text_file.write(str(i) +"\n"+ filedata)
            text_file.close()
        i += 1
    properdivisor(starttimer)

def properdivisor(starttimer):
    file = open("numbers.txt", "r")
    highest = file.readlines()
    print("\nThe Highest Proper Divisor Is\n--------\n" + highest[1] + "--------" + "\nIt took"  ,round(time.time() - starttimer, 2)  ,"seconds to finish finding the divisors.\n")
    restart(errorrestart = "false")

def restart(errorrestart):
    if errorrestart == "false":
        input("Do You Want Restart?\nPress Enter To Restart Or Close The Programe To Leave")
        start()
    elif errorrestart == "true":
        input("\nThere Was An Error Detected.\nPress Enter To Restart Or Close The Programe To Leave")
        start()

def error(error):
    print("\n----------------------------------\nERROR - " + error + "\n----------------------------------")
    restart(errorrestart = "true")

clearfile(name = "numbers")
start()
def clearfile(名称):
文件=打开(名称+“.txt”,“r”)
filedata=file.read()
file.close()文件
text_file=open(name+“.txt”,“w”)
文本文件。写入(“”)
text_file.close()
def start():
num=输入(“输入您的号码:”)
检查(数字)
def检查(num):
尝试:
intnum=int(num)
除值错误外:
错误(error=“无效数字”)
如果(intnum<0):
错误(error=“仅限正数”)
其他:
finddivisor(intnum)
def finddivisor(intnum):
starttimer=time.time()
i=1
打印(“\n数字的除数为:”),

而i如果你有一个数
n
的除数
a
,那么你可以告诉另一个数
n
b=n/a
。此外,如果
a=sqrt(n)
,反之亦然。这意味着在
finddivisor
函数中,您可以在
i*i时进行迭代,而无需在每次要将单个条目放入整个文件时读取和重写整个文件。当你知道你想要什么样的改变时,你可以只做一次。你也可以附加到它上面。也许是这样的:

def finddivisor(intnum):
    starttimer = time.time()
    print("\nThe divisors of your number are:")
    divs = set()
    for i in range(1, int(math.sqrt(intnum)) +1):
        if intnum % i == 0:
            print(i)
            divs.add(i)
            divs.add(intnum // i)
    with open("numbers.txt", "a") as file:
        file.writelines("{}\n".format(ln) for ln in sorted(divs, reverse=True))
此外,您的程序流正在构建一个非常深的堆栈。试着用类似的东西把它压扁

def start():
    clearfile()
    while True:
        n = get_number()
        starttimer = time.time()
        finddivisor(n)
        properdivisor(starttimer)
        input("Press Enter To Restart Or Close The Programe To Leave")
properdivisor
中,您也不需要读取整个文件,只需要第一行。所以可能是这样的:

def properdivisor(starttimer):
    with open(FILENAME, "r") as file:
        highest = file.readline().strip()
    print "\nThe Highest Proper Divisor Is"
    print "--------%s--------" % highest
    print "It took %0.2f seconds to finish finding the divisors.\n" % (time.time() - starttimer)
编辑后

我会这样做,它在我的盒子上运行不到一秒钟:

import math

def get_divisors(n):
    yield 1
    sqroot = int(math.sqrt(n))
    for x in xrange(2, sqroot):
        if n % x == 0:
            yield x
            yield n / x
    if sqroot**2 == n:
        yield sqroot

divisors = sorted(get_divisors(999999999999))
print divisors

不要多次
打开
关闭
文件此问题似乎与主题无关,因为它属于打开状态。是否必须在文件中存储中间值?如果您只需将其保留在内存中,它也将有助于LOT,
clearfile
只需要是
def clearfile(name):以open(name,'w')作为f:pass
;您打开文件两次,但从不使用
filedata
。user1603472不,我不必存储它们。我决定这样做,这样我可以在wards之后看到我的结果并更好地阅读它们,但实际上不需要将它们存储在文件中。将它们存储在内存中很好。感谢您指出,我不需要在每次循环运行时都关闭文件,所以我会将关闭文件移到重新启动位。它对计算数字所需的时间也有很小的影响。是的,在这种情况下,文件操作对时间没有显著影响。但若你们考虑到除数(i,n/i)的概念,你们会得到渐进的加速。我们刚刚试了5000次,得到了相同的时间,但它用了38秒,从999999999,这是一个伟大的start@OliverPerring:您没有使用Effect的主要建议,即在每次迭代中查找两个除数,当你通过输入的平方根时停止。我再次编辑了代码,现在它位于问题的底部,但是@JohnY you是对的,我应该一直编辑到平方根为止。对不起,看得太多了,这不会增加两次平方根吗?我理解这段代码,直到打开(“numbers.txt”,“a”)我不太明白那是怎么回事。抱歉,如果我变暗了,我确信这很明显。
open
使用
'a'
以附加模式打开文件
with
是一个文件上下文管理器,确保它关闭。@Cole这就是为什么
divs
是一个
set
的原因。既然用这种方式添加它们是无序的,那也没什么坏处。哦,好吧,handy知道这有什么限制吗?或者我应该总是用它来代替“w”和“r”吗
def properdivisor(starttimer):
    with open(FILENAME, "r") as file:
        highest = file.readline().strip()
    print "\nThe Highest Proper Divisor Is"
    print "--------%s--------" % highest
    print "It took %0.2f seconds to finish finding the divisors.\n" % (time.time() - starttimer)
import math

def get_divisors(n):
    yield 1
    sqroot = int(math.sqrt(n))
    for x in xrange(2, sqroot):
        if n % x == 0:
            yield x
            yield n / x
    if sqroot**2 == n:
        yield sqroot

divisors = sorted(get_divisors(999999999999))
print divisors