In: Computer Science
Can you tell me what is wrong with this code ?
def update_char_view(phrase: str, current_view: str, index: int,
guess: str)->str:
if guess in phrase:
current_view = current_view.replace(current_view[index],
guess)
else:
current_view = current_view
return current_view
update_char_view("animal", "a^imal" , 1, "n")
'animal'
update_char_view("animal", "a^m^l", 3, "a")
'aamal'
Answer:
What's wrong in your code?
current_view = current_view.replace(current_view[index], guess)
at that line when you are trying to replace the value at that index the replace method will take two argument first argument which denotes the string to be replaced with second argument. So when you are giving the index value at that particular index value thre is '^' so the replace method checks '^' for that character all over the string and its replacing with the guess character which we don't need that. according to your code your only requirment is to replace the guessed string at the given index so we need to update the above statement using string slicing and concatenation
here is the updated line : current_view=current_view[:index]+guess+current_view[index+1:]
and that else condtion in your code doesn't make any sense you can remove that
Python code:
Raw code:
def update_char_view(phrase: str, current_view: str, index: int, guess: str)->str:
if guess in phrase:
current_view=current_view[:index]+guess+current_view[index+1:]
return current_view
print(update_char_view("animal", "a^imal" , 1, "n"))
print(update_char_view("animal", "a^m^l", 3, "a"))
Editor:
output;
Hope this helps you! If you still have any doubts or queries please feel free to comment in the comment section.
"Please refer to the screenshot of the code to understand the indentation of the code".
Thank you! Do upvote.