Assuming two equal length strings, how can I check if the elements at the same number index match? For example, I want to check if the letters in a partially guessed word ('ap_le') match with letters at the same index in a complete word ('apple'). So in that example, the function would ideally return True.
However, I'm not receiving any output and I believe the issue may be in the line: if mw[ltr] == ow[ltr]. I ran it trough pythontutor and it said there was a syntax error here, and I'm not sure how to check the sameness of element and index.
import string
def match_with_gaps(guess, correct_word):
g = list(guess.replace(' ',''))
cw = list(correct_word)
indices = [idx for idx, x in enumerate(g) if x in string.ascii_lowercase]
for ltr in indices:
if g[ltr] == cw[ltr]:
return True
return False
match_with_gaps('ap_ le', 'apple')
You're just missing a colon in your if statement for the syntax error. I'm not sure where mw
or ow
are coming from, but I would use your variables from the list above then flip the logic to return false if there isn't a match only returning True
if all indices
match. Try this:
import string
def match_with_gaps(guess, correct_word):
g = list(guess.replace(' ',''))
cw = list(correct_word)
indices = [idx for idx, x in enumerate(g) if x in string.ascii_lowercase]
for index in indices:
if g[index] != cw[index]:
return False
return True
match_with_gaps('ap_ le', 'apple')
Happy coding!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.