python 中的 try 语句在大多数情况下都会失败,其时间复杂度是多少?

What is the time complexity of a try statement in python given that it will fail a majority of the time?

我有一个函数,我想在其中检测字符串中任何字母(给定一组字母)的第一次出现以及 return 字母的索引(见下文)。

时间很紧迫,所以我正在考虑使用 try/except 方法(请参阅下面的 LetterDetect)。

知道 try 语句大多数时候都会失败,这是一种不好的做法吗?其次,这是否比检查每个字典条目中每个字母的出现(如 LetterDetect2)更有效(时间方面)?

取下面的函数看起来:

def LetterDetect(s, letters):
    Dct = {}
    for l in letters:
        Dct[ord(l)] = 0

    for i in range(0, length(s)):
        try:
            Dct[ord(s[i])] +=1
            return i
        except:
            pass

对战:

def LetterDetect2(s, letters):
    Dct = {}
    for l in letters:
        Dct[ord(l)] = 0

    for i in range(0, length(s)):
       if ord(s[i]) in Dct:
            return i

LetterDetect("test", "abcdt")
LetterDetect2("test", "abcdt")

感谢任何帮助,我是编码新手 Python。谢谢!

使用字典似乎是解决此问题的一种奇怪方法。您使用它有什么具体原因吗?

字符串方法 .find() https://docs.python.org/2/library/stdtypes.html#str.find 似乎是一个更好的解决方案:

def LetterDetect(s, letters)
    for l in letters:
        position = s.find(l)
        if position != -1:
            return position
    return None

除了 John Gordon 指出的您设计的基本问题外,我想直接回答问题:

  1. 用try/catch来实现普通的流量控制是滥用其目的。我可以预测这可能会影响您的几种方式(调试器可能会在异常时阻止您,未来的程序员可能 "correct" 您的代码)但基本规则是,按设计使用语言功能。
  2. 实际上,try/catch 会很慢。语言运行时必须参与并做各种奇特的事情,none 你确实需要。
  3. 例外应该是例外。