Jungle Camping Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

9th Aug 2022, 10:46 PM
Wesley Harwell
Wesley Harwell - avatar
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
9th Aug 2022, 11:07 PM
PanicS
PanicS - avatar
0
Could you make a code example?
9th Aug 2022, 10:50 PM
ρү૨œdԌ૨ ×
ρү૨œdԌ૨ × - avatar
0
I cant remember if dictionaries are mutable...
9th Aug 2022, 10:52 PM
ρү૨œdԌ૨ ×
ρү૨œdԌ૨ × - avatar
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.
9th Aug 2022, 10:54 PM
ρү૨œdԌ૨ ×
ρү૨œdԌ૨ × - avatar
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
9th Aug 2022, 10:58 PM
ρү૨œdԌ૨ ×
ρү૨œdԌ૨ × - avatar
0
I was way wrong lol .. i tried
9th Aug 2022, 11:10 PM
ρү૨œdԌ૨ ×
ρү૨œdԌ૨ × - avatar