0
Jungle Camping Python
I'm not sure why my code is working for 1, 2, and 4 but not cases 3&5. I can't view them so I'm not sure what the actual output is that's causing it to fail. Code is as follows x = input() y = x.split(" ") z = {"Grr": "Lion", "Ssss": "Snake", "Rawr": "Tiger", "Chirp": "Bird"} for word in y: t = x.replace(word, z[word]) print(t)
6 Answers
+ 5
Your code replace only last instance and keep others unchanged, so if input is:
Grr Ssss - it should output Lion Snake, but it exualy output Grr Snake, if we run print inside for loop we would see this as output:
First run - Lion Ssss
Second - Grr Snake
So it change only current one but keep prev one unchanged
Reason why this is heppening is because of replace method
replace is not changing original string it just save new string to variable
I solved this problem with next code:
x = input()
y = x.split(" ")
z = {"Grr": "Lion", "Ssss": "Snake", "Rawr": "Tiger", "Chirp": "Bird"}
t = ""
for word in y:
t += z[word] + " "
# print(t.strip()) - will remove this extra space
print(t)
It is not perfect because it have extra space at end, but it pass sololearn test, if you use yourString.strip() extra spaces will be removed
0
Could you make a code example?
0
I cant remember if dictionaries are mutable...
0
A dict is mutable but is addresses by its keys. So like z[0] it should be z[key] .. im guessing dictionaries are not indexed.. if you know exactly what I mean. I hope I help..
Correct I was. dicts are not indexed therefore they are called by their keys, instead of place in an order.
0
Also is it not redundant to x.replace(word, z[word]) replacing and searching for the same word where it appears not correctly referencing the dictionary key:value
0
I was way wrong lol .. i tried