【问题标题】:Find matching characters in two strings with same and different positions在具有相同和不同位置的两个字符串中查找匹配字符
【发布时间】:2020-09-02 09:11:26
【问题描述】:

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

例如:

# vowel in wrong index
>>> def compute_value_for_guess('aecdio', 3, 4, 'ix')
5
# vowel in correct index
>>> def compute_value_for_guess('aecdio', 3, 4, 'xi')
14
# multiple matches
>>> def compute_value_for_guess('aecdio', 1, 4, '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 来表示辅音。

【问题讨论】:

    标签: python string for-loop if-statement


    【解决方案1】:

    您的代码(在我看来)在被猜测的单词上做了一个不必要的循环,看起来过于复杂。

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 2015-08-05
      相关资源
      最近更新 更多