我應該如何制作一個函式,該函式將回傳匹配數字來自字串的位置。
def foundInPosition(secretString, guess):
"""
Returns the number of matching digits between the guess and
the secretString. For example when secretString is "12345"
and the user's guess is "12675"' this function should return 3
as the 1, 2 and 5 all have the same value at the same location.
foundInPosition("12345", "19395") returns 3
foundInPosition("12345", "99399") returns 1
"""
# TODO: Complete this function
return
# Test foundInPosition.
assert(foundInPosition("12345", "99999") == 0)
assert(foundInPosition("12345", "19999") == 1)
assert(foundInPosition("12345", "12999") == 2)
assert(foundInPosition("12345", "12399") == 3)
assert(foundInPosition("12345", "12349") == 4)
assert(foundInPosition("12345", "12345") == 5)
assert(foundInPosition("12345", "19395") == 3)
assert(foundInPosition("12345", "19395") == 3)
assert(foundInPosition("92345", "90000") == 1)
uj5u.com熱心網友回復:
一個簡單的答案是這樣的:
def foundInPostion(secretString, guess):
count = 0
for d in range(0,5):
if secretString[d] in guess:
count = 1
return count
它將查看您的 secretString 中有多少個單個字符在您的猜測字串中重復,并且范圍從 0 到 5,因為您給出的所有情況都只有 5 個字符,您可以使用它for d in range(0, len(secretString))來使您的代碼更多動態的,在這種情況下,無論長度secretString是多少,它都會走那么多
uj5u.com熱心網友回復:
這可以使用串列理解在單行中完成。您可以遍歷字串中的字符并進行比較檢查。
sum([1 if guess[i] == secretString[i] else 0 for i in range(len(secretString))])
或者,您可以更明確,更可能在您的情況下,您可能想要解釋每個步驟,將其分解為字符的 for 回圈并使用 if 陳述句進行檢查。
count = 0
for i in range(len(secretString)):
if secretString[i] == guess[i]:
count = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362720.html
