How should I go about making a function that will return where the matching digits are from a string.
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)
CodePudding user response:
A simple answer would be like this:
def foundInPostion(secretString, guess):
count = 0
for d in range(0,5):
if secretString[d] in guess:
count = 1
return count
it is going to see how many of the single chars in your secretString are repeated in your guess string, and the range is given from 0 to 5 because all the cases you gave have only 5 chars, and you could use for d in range(0, len(secretString))
to make your code more dynamic, in this case however the length of the secretString
is, it will go that much
CodePudding user response:
This can be done in a one-liner using list comprehension. You can iterate over characters in a string and just check them comparatively.
sum([1 if guess[i] == secretString[i] else 0 for i in range(len(secretString))])
Or, you could, to be more explicit and likely in your case you may want to explain each step, break it into a for loop over the characters and check using an if statement.
count = 0
for i in range(len(secretString)):
if secretString[i] == guess[i]:
count = 1