哪个代码更适合在字符串中查找第一个重复出现的字母? [关闭]

问题描述 投票:-2回答:2

第一个代码是:

 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

这两个代码都有效,但我不知道哪个代码性能更好。

python algorithm search
2个回答
0
投票

创建一个计时器功能如下,并用它装饰你的功能,并自己查看结果。

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():

0
投票

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

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

'''
end = time.time()

print(start - end)
© www.soinside.com 2019 - 2024. All rights reserved.