Reputation: 41
I have a person calling a function with three inputs:
puzzle
- so a random word, for example. 'john'view
- their view of the puzzle (they guess letters and they become revealed scoring points, etc) so lets say they only see j^h^
(^ represents hidden characters).letter_guessed
- they guess a letter, so if someone guessed 'o'
, the view would come back as 'joh^'
But my code just doesn't seem work and I can't seem to understand why, and please if you could do it using my bit of code below, I understand there are many ways to solve it but I'm interested in what I had to do if I wanted to solve this question using a for
statement with nested if
statements.
What it doesnt do: it simply displays the view again, the line of incorrect code is result = result + letter because i dont know how to make python scan for the hidden variable and replace the ^ with set found alphabetic letter.
def update_view(puzzle,view,letter_guessed):
result = ""
for index in range(0,len(puzzle)):
if puzzle[index] == letter_guessed:
result = result + letter_guessed
else:
result = view
return result
Upvotes: 0
Views: 123
Reputation: 42450
If the letter is currently "^" and the letter was guessed correctly, you want to add the guessed letter to result. Else, you want to add whatever was on the view earlier
def guess(word, view, letter) :
result = ""
for i in range(0,len(word)) :
if view[i] == "^" and word[i] == letter:
result += word[i]
else :
result += view[i]
return result
The above if-else
condition can be further shortened using Python's true if condition else false
construct
def guess(word, view, letter) :
result = ""
for i in range(0,len(word)) :
result += word[i] if view[i] == "^" and word[i] == letter else view[i]
return result
Upvotes: 4