Method 1 - Conventional
if/else
:
from collections import Counter
sentence = Counter(input("What would you like to say? ").lower())
sentence_length = 0
for k, v in sentence.items():
if v > 1:
print("There are {} {}'s in this sentence.".format(v, k))
else:
print("There is {} {} in this sentence.".format(v, k))
sentence_length += v
print("There are {} words, including spaces, in total.".format(sentence_length))
^{2}$
from collections import Counter
sentence = Counter(input("What would you like to say? ").lower())
sentence_length = 0
for k, v in sentence.items():
print("There {} {} {}{} in this sentence.".format(("are" if v > 1 else "is"), v, k, ("'s" if v > 1 else "")))
sentence_length += v
print("There are {} words, including spaces, in total.".format(sentence_length))
这两个代码段都用于计算特定字符在句子中出现的次数。这两种方法的区别在于“for”语句内部的部分-条件字符串格式或常规if/else。我在想哪种方法更有效。你知道吗
由于两者在算法上没有区别,所以回答这个问题的唯一方法就是测试它。他说
当然,很难对包含
input
的程序进行基准测试,因此首先我计算了键入所需句子所花的时间,然后用常量赋值和time.sleep(7.8)
替换了它。他说两个版本都用了不到8秒的时间。7.8秒以外的大部分时间都花在
print
。他说但是,根据{},版本1比版本2快了约0.0005秒,加速率约为0.006%。他说
(顺便说一句,你得到的加速比从
str.format
到%
要快得多。)我敢肯定,几乎所有的差异都归结为
str.format
有更多的参数,而不是if
语句和if
表达式之间的差异。他说当然,细节可能取决于您选择的Python实现,也可能取决于您的版本和平台,取决于您输入的字符串,最重要的是,您输入的速度有多快。所以,如果这0.006%的差异对某些东西来说很重要,你真的需要自己测试一下。他说
相关问题 更多 >
编程相关推荐