我想返回一个分数,如果用户猜测的字符与他们正在猜测的单词的子字符串中的字符相同。对于被猜测的元音和辅音以及它们是否处于正确的位置,有不同的分数
例如:
# 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
辅音
在我看来,您的代码在被猜测的单词上做了一个不必要的循环,看起来过于复杂
我在这里提出了改进代码的建议:
相关问题 更多 >
编程相关推荐