[英]Find matching characters in two strings with same and different positions
如果用戶猜測的字符與他們猜測的單詞的 substring 中的字符相同,我想返回一個分數。 元音和輔音被猜到的位置是否正確都有不同的分數。
例如:
# 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
。
您的代碼(在我看來)對被猜測的單詞做了一個不必要的循環,看起來過於復雜。
我在這里發布我對改進代碼的建議:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.