简体   繁体   English

我需要一种更有效的方法来查找另一个字符串中是否包含一个字符串

[英]I need a more efficient way to find if a word of strings is in another string

I'm trying to write a function with two input, word, and a dictionary. 我正在尝试用两个输入,单词和一个字典编写一个函数。 I already wrote a very inefficient version. 我已经写了一个效率很低的版本。 The keys of the dictionary are letters with positive integers as keys. 字典的键是带有正整数作为键的字母。 The function returns True if all letters in the word are in the dictionary and subtract one from the value every letter in the word from the dictionary or False if any of the letters in the word is not in the dictionary and will not change the value of the dictionary even if some of the letters are present. 如果单词中的所有字母都在字典中,则该函数返回True,然后从字典中该单词中的每个字母的值中减去一个;如果单词中的任何字母不在字典中且不会更改的值,则该函数返回False。即使有些字母出现在字典中。 Here is my version 这是我的版本

def isWordIn(word, store):
"""Input: word and store are strings and list respectively
   Output: True or False
""" 
    for letter in word:
        if letter not in store.keys():
            return False

        for letter in word:
            if letter in store.keys():
                store[letter] -= 1
        return True

find(str, beg=0, end=len(string)) : Determines whether str occurs in a string and outputs the index of the location. find(str, beg=0, end=len(string)) :确定str是否出现在字符串中并输出位置索引。 You can limit the search by specifying a beginning index using beg or a ending index using 您可以通过以下方式限制搜索:使用beg指定开始索引,使用

store.find(word) can be used in your situation without the need to create a seperate function. store.find(word)可以在您的情况下使用,而无需创建单独的函数。 Remember, this will return the index of the location. 请记住,这将返回位置的索引。

Official Python Docs: https://docs.python.org/3/library/stdtypes.html?highlight=find#str.find 官方Python文档: https : //docs.python.org/3/library/stdtypes.html? highlight = find# str.find

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM