![](/img/trans.png)
[英]Why does my code give me the wrong result when adding negative numbers in Python?
[英]Why does my wordle logic give the wrong result when the character in the guess is repeated too many times?
遵循 wordle 的原則,檢查每個猜測並給出五個字母 output。 G代表綠色代表相同且位置正確的字母,黃色代表相同位置錯誤的字母,B代表不匹配。
def output_guess(guess:str, word: str, dictionary: list):
"""
Checks guess for game errors, and outputs current "score" to user
parameters: user's guess, word from dictionary, dictionary
return: none
"""
output = ""
if len(guess) == 5 and guess in dictionary:
for i in range(len(word)):
if guess[i] == word[i]:
output += "G"
elif guess[i] in word:
output += "Y"
else:
output += "B"
else:
print("Word not found in dictionary. Enter a five-letter english word.", end = "")
print(output)
例如,如果答案是五個字母的單詞 eerie,我希望收到以下猜測的這些輸出:
Guess 1: epees GBYYB
Guess 2: peeve BGYBG
Guess 3: order BYBYB
Guess 4: eerie GGGGG
除了猜測 3,我對代碼的所有猜測都收到正確的 output。對於猜測 3:順序,我得到 BYBYY 而不是 BYBYB。
你的邏輯不正確。 僅僅檢查單詞中是否存在該字符是不夠的,您還需要計算輸入中的字符並確保單詞中的字符數相等或更小
import collections
word = "eerie"
guess = "order"
word_counts = collections.Counter(word) # Count characters in the word
guess_counts = collections.defaultdict(int) # Create an empty dict to count characters in guess
output = []
for g, w in zip(guess, word):
guess_counts[g] += 1 # Add to count of current character
if g == w:
# Correct character, correct position
output += "G"
elif guess_counts[g] <= word_counts[g]:
# The minimum that `guess_counts[g]` can be is 1
# Why? We set it in the first line of this loop
# For this condition to be true, word_counts[g] must be > 0
# (i.e `word` must contain `g`)
# And we must have seen `g` fewer (or equal) times than
# the word contains `g`
output += "Y"
else:
output += "B"
print(output)
我使用collections.Counter
而不是手動計算字母,和collections.defaultdict(int)
所以我不需要在遞增之前檢查字典是否包含字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.