【发布时间】:2019-12-02 01:15:39
【问题描述】:
在尝试查找字符串中一堆字符的频率时,为什么对 4 个不同的字符运行 string.count(character) 4 次会比使用集合产生更快的执行时间(使用 time.time())。计数器(字符串)?
背景: 给定由字符串表示的一系列移动。有效的移动是 R(右)、L(左)、U(上)和 D(下)。如果移动序列将我带回原点,则返回 True。否则,返回假。
# approach - 1 : iterate 4 times (3.9*10^-6 seconds)
def foo1(moves):
return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R')
# approach - 2 iterate once (3.9*10^-5 seconds)
def foo2(moves):
from collections import Counter
d = Counter(moves)
return d['R'] == d['L'] and d['U'] == d['D']
import time
start = time.time()
moves = "LDRRLRUULRLRLRLRLRLRLRLRLRLRL"
foo1(moves)
# foo2(moves)
end = time.time()
print("--- %s seconds ---" % (end - start))
这些结果与我的预期相反。我的理由是第一种方法应该花费更长的时间,因为字符串迭代了 4 次以上,而在第二种方法中,我们只迭代了一次。可能是由于库调用开销造成的吗?
【问题讨论】:
-
请提供一个可重现的例子。请注意,您的第一个“应用程序”除了定义一个函数之外什么都不做……您的实际字符串是什么?第二种方法可能会缩放更好,但实际上对于小字符串可能不会更快。
-
@juanpa.arrivillaga 我添加了更多细节。我想你可能是对的。但是,这个问题来自 leetcode leetcode.com/problems/robot-return-to-origin,我得到的结果是(方法 1 为 20 ms,方法 2 为 90 ms,这让我感到疑惑)。他们通常有输入很长的边缘测试用例,但我无法确定,因为我看不到他们在此上运行的测试用例。
-
旁注:一个小的优化机会,不管你怎么做,如果输入字符串的长度是奇数,则返回
False。由于返回原点必须将每一步都与相反的移动配对,所以奇数长度肯定不会通过。
标签: python-3.x count counter performance-testing performancecounter