Issue
If I have a function:
def chars(str1: str, str2: str, str3: str) -> str:
What should I put inside this so that it returns a new string where the character at index i is str1[i] if str3[i] is 0 and str2[i] if str3[i] is 1.
for example, if I had:
chars('dog', 'cat', '001')
it would output:
dot #since the first 0 is d from str1, the second 0 is o from str1 and the 1 is t from str2
Another example could be:
chars('army', 'game', '0011')
it would output:
arme ##since the first 0 is a from str1, the second 0 is r from str1, the first 1 is m from str2 and the second 1 is e from str2
This is what I tried so far:
for i in range(len(str3)):
if str3[i] == '0':
return str1[i]
else:
return str2[i]
but it only returns the first letter and nothing else so how would I fix this?
Solution
The code can be fixed by adding a variable
def chars(str1: str, str2: str, str3: str) -> str:
final = "" # I added a variable with name final
for i in range(len(str3)):
if str3[i] == '0':
final += str1[i]
else:
final += str2[i]
return final
print(chars("dog", "cat", "001")) # For testing purpose
Here the code goes as follows final = ""
- str3[0] = 0 so final = final + str1[0] -> final = "d"
- str3[1] = 0 so final = final + str1[1] -> final = "do"
- str3[2] = 1 so final = final + str2[2] -> final = "dot" return final -> "dot"
Answered By - Pavan Akurathi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.