python-3.x - 如何最大化python效率?
问题描述
我正在处理一个代码信号练习面试问题,我的代码通过了 16/19 测试,但由于超过了允许的时间限制,其余的测试都失败了。
我尝试使用set()
而不是列表,但计数方法不起作用,而且由于我对 python 非常陌生,我不知道更好的选择。
def firstNotRepeatingCharacter(s):
list = []
num = '_'
for i in s:
list.append(i)
for i in list:
if list.count(i) <= 1:
num = i
return num
return num
解决方案
如果您使用的是 Python 3.7+,其中 dict 键是按插入顺序排列的,您可以使用collections.Counter
:
from collections import Counter
def firstNotRepeatingCharacter(s):
return next((char for char, count in Counter(s).items() if count == 1), '_')
在 Python 的早期版本中,您可以使用它collections.OrderedDict
来跟踪计数:
from collections import OrderedDict
def firstNotRepeatingCharacter(s):
counts = OrderedDict()
for char in s:
counts[char] = counts.get(char, 0) + 1
return next((char for char, count in counts.items() if count == 1), '_')
这样firstNotRepeatingCharacter('aababdcbcea')
返回:'d'
由于您在循环中使用该方法,上述两个代码片段的时间复杂度均为O(n),而您的解决方案中的时间复杂度为 O (n ^ 2) 。list.count
推荐阅读
- java - 引诱没有正确报告失败异常( nosuchelementexception )
- graphql - GraphQL:字段解析器未在订阅查询中触发?
- php - 是否可以在查询 PHP Mysql 中减少一次以上?
- c# - 从 SQL 数据库添加图像时,ImageList 引发“内存不足”异常
- formula - 使用 SUMPRODUCT 而不是 SUMIFS
- android - Google Firebase 添加应用,SHA 问题
- javascript - 注释中的装饰器对代码有影响吗?
- javascript - 捆绑失败:错误:需要 Babel "^7.0.0-0"
- python - 在列表对象上调用 IF 语句会发生什么?调用什么方法来判断是真还是假?
- powershell - 将字符串转换为 int 并仅为 TFS 中的内部版本号递增最后一位