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

2024-09-29 23:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

# 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辅音


Tags: inforindexifvaluedefstartword
1条回答
网友
1楼 · 发布于 2024-09-29 23:18:25

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

我在这里提出了改进代码的建议:

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

相关问题 更多 >

    热门问题