微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在位置相同和不同的两个字符串中查找匹配的字符

如何解决在位置相同和不同的两个字符串中查找匹配的字符

如果用户的猜测中的字符与他们猜测的单词的子字符串中的字符相同,我想返回一个分数。元音和辅音的猜测分数以及它们是否在正确的位置都有不同的分数。

例如:

# vowel in wrong index
>>> def compute_value_for_guess('aecdio',3,4,'ix')
5
# vowel in correct index
>>> def compute_value_for_guess('aecdio','xi')
14
# multiple matches
>>> def compute_value_for_guess('aecdio',1,'cedi')
36

这是我到目前为止的尝试:

VOWELS = "aeIoU"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"

def compute_value_for_guess(word,start_index,end_index,guess):
    """
    word(str): word being guessed
    start_index,end_index(int): substring of word from start_index up to and including 
    end_index
    guess(str): user's guess of letters in substring
    """
    score = 0
    for ia in range(len(word[start_index:end_index+1])):
        for ib in range(len(guess)):
            if word[ia] in VOWELS and guess[ib] in VOWELS:
                if guess[ib] in word[start_index:end_index+1]:
                    if ia == ib:
                        score += 14
                    elif ia != ib:
                        score += 5
                else:
                    score += 0
            elif word[ia] in CONSONANTS and guess[ib] in CONSONANTS:
                    if guess[ib] in word[start_index:end_index+1]:
                        if ia == ib:
                            score += 12
                        elif ia != ib:
                            score += 5
                    else:
                        score += 0

我获得了一些元音值,但它们不正确,并且它会不断返回0的辅音。

解决方法

(在我看来,您的代码确实对正在猜测的单词进行了一个不必要的循环,并且看起来过于复杂。

我在这里发表了对改进代码的建议:

VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"

def compute_value_for_guess(word,start_index,end_index,guess):
    """
    word(str): word being guessed
    start_index,end_index(int): substring of word from start_index up to and including 
    end_index
    guess(str): user's guess of letters in substring
    """
    score = 0
    substring = word[start_index:end_index+1]
    print (substring)
    for ib in range(len(guess)):
        # check if the char is in the substring
        if guess[ib] in substring:
            # increase score depending on position and vowel/consonant
            if substring[ib] != guess[ib]:
                score += 5
            elif guess[ib] in VOWELS:
                score += 14
            else:
                score += 12

    # return the score!
    return score

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。