【问题标题】:my function keeps checking the same index instead of checking the other index我的函数不断检查相同的索引而不是检查另一个索引
【发布时间】:2022-01-24 12:11:29
【问题描述】:
def capital_indexes(word):
    letters = []

    capital_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

    index_letters = []

    # append letters in the word to a list
    for letter in word:
        letters.append(letter)

    # go through the letters in the list letters
    for i in letters:
        # checks if the indexes in the list match with the indexes in the list 'capital_leters'
        if i in capital_letters:
            index_letters.append(word.index(i))

    return index_letters


word_capital = capital_indexes('TEsT')
# this should return (0, 1, 3) but it keeps returning (0, 1, 0)

print(word_capital)

【问题讨论】:

  • 不知何故,这个 leetcode 是今天的问题吗?

标签: python list


【解决方案1】:

.index 返回第一个出现的字母,使用enumerate.isupper

def capital_indexes(word):
    return [i for i,l in enumerate(word) if l.isupper()]

【讨论】:

    【解决方案2】:

    您的代码效率非常低,例如转换为列表是无用的(您可以遍历字符串),然后循环遍历所有大写字母也是低效的(而是使用集合)。最后,您的主要错误在于 word.index(i) 将始终返回 first 匹配的位置(因此 0 代替 3)。

    这是一个替代解决方案:

    def capital_indexes(word):
        # general case for any given set of characters
        from string import ascii_uppercase
        letters = set(ascii_uppercase)
        return [i for i,c in enumerate(word) if c in letters]
        # case for uppercase only
        # return [i for i,c in enumerate(word) if c.isupper()]
            
    capital_indexes('TEsT')
    # [0, 1, 3]
    

    【讨论】:

    • “到列表的转换是无用的(你可以迭代一个字符串” - 看起来他们已经知道了,因为他们正在迭代字符串进行转换:-)
    • @Kelly in for i in letters:, letters 是一个列表
    • 不知道你为什么这么说。在for letter in word: 中,word 是一个字符串
    • 好吧,他们应该在测试字符时直接这样做,构建列表没有用
    【解决方案3】:

    这是因为 T 在索引 0 和索引 3 处,所以索引 0 被返回两次。

    试试:

    import string
    
    result = [i for i, char in enumerate(word) if char in string.ascii_uppercase]
    

    在你的例子中:

    >>> word = "TEsT"
    >>> [i for i, char in enumerate(word) if char in string.ascii_uppercase]
    
    [0, 1, 3]
    

    【讨论】:

    • 宁可使用集合(见my answer),重复搜索字符串中的字符代价高
    • 公平点,平均而言,一组时间是恒定的 - wiki.python.org/moin/TimeComplexity。然而,列表很小并且固定在这里,所以不太重要。
    • 嗯,这不是原始代码中最糟糕的,但仍然是一个好习惯。编码中的一件重要事情也是尝试学习优化以准备使用生产代码;)
    • @mozway 或'A' <= char <= 'Z'。不知道哪个更快...
    • @Kelly 双重比较比设置索引慢约 60%
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2020-01-30
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多