Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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_Algorithm_Search - Fatal编程技术网

Python 哪种代码更适合查找字符串中的第一个循环字母表?

Python 哪种代码更适合查找字符串中的第一个循环字母表?,python,algorithm,search,Python,Algorithm,Search,第一个代码是: string = "DBCABA" #computing the first recurring alphabet def compute_reccuring(): for a in string: var = string.count(a) if var > 1: final = str(a) print(str(final) + " is repeated first")

第一个代码是:

 string = "DBCABA"
 #computing the first recurring alphabet
 def compute_reccuring():
     for a in string:
         var = string.count(a)
         if var > 1:
            final = str(a) 
        print(str(final) + " is repeated first")
        break
第二个代码是:

def recurring():
    counts = {}
    for a in string:
        if a in counts:
           print(a)
        else:
           counts[a] = 1

这两个代码都可以工作,但我不知道哪一个性能更好。

创建一个计时器函数,如下所示,并用它装饰您的函数,然后自己查看结果

import time                                                

def timeme(method):
    def wrapper(*args, **kw):
        startTime = int(round(time.time() * 1000))
        result = method(*args, **kw)
        endTime = int(round(time.time() * 1000))

        print(endTime - startTime,'ms')
        return result

    return wrapper
然后可以将此函数用作函数的装饰器。大概是这样的:

@timeme
def recurring():

您可以使用下面的代码检查脚本运行所花费的时间

import time
start = time.time()
'''
Your Code

'''
end = time.time()

print(start - end)

创建一个足够大的字符串并尝试测试性能。string.count是一个隐式循环。此外,在第二个示例中,如果a in计数。。可能应该在外部/之前终止。因此,在我看来,第一个在^2上,对于每个a in字符串,您在.counta中再次遍历整个字符串,而第二个在^2上,因为您使用的是dict计数,其恒定访问时间为O1,所以,仅通过查看代码,我认为第二个更好,在第二种情况下,你需要在内存中保存一个dict,这样可能需要更多的内存。。。取决于你认为什么更好…更快?内存少了?谢谢。它显示了这两个功能的时间,但是内存呢?可能是你可以尝试的。希望有帮助。