+ 2
SoloLearn "code coach challenge" - "Jungle Camping" solved but I need to know if I can improve my logic in solving this problem
Input is a single string of animal sounds and output should have a single string with their respective animal names. I have attached the code to this question. I have used a dictionary,list,for loop, if condition, split and join function. Is there anything I am missing in my code? In order to make it simpler. Or may be I can try any other better logic to solve this problem? I am new to Python and would appreciate any help/feedback/suggestions. Thank you https://code.sololearn.com/cfHbhSV4Hjza/?ref=app
4 odpowiedzi
+ 2
I like your solution and wouldn't change too much. You've got some error handling, which is not really required for the code coaches, but no reason to leave it away. You could directly split the input to a list on reading (and change your error handling to case of empty list). And your variable names are a little strange. They are not really "meaningful". Accessing the dictionary could be done easier combined with error handling (just try to append, except append this "unknown").
+ 1
@Sandra Meyer
I appreciate your time in reviewing my code and thank you for the suggestions.
It will help me in following the best practices.
Modified the below in my code, based on your suggestions.
1) Added split function on reading (It reduced the count of variables used)
2) Tried adding meaningful names to the variables (May improve the code readability)
3) Accessing the dictionary using try and except (Looks simpler now)
Looking forward to learn more.
//New code below:
animal_sounds = {'grr': 'Tiger', 'sss': 'Snake', 'chirp': 'Bird'}
sounds = input().split(',')
if sounds == ['']:
print("No sound heard")
exit()
animals = []
for i in sounds:
try:
animals.append(animal_sounds[i])
except:
animals.append("Unknown")
print(' '.join(animals))
Thanks again!
+ 1
sounds=['Grr','Rawr','Ssss','Chirp']
animal=['Lion', 'Tiger','Snake','Bird']
print(' '.join(map(lambda x:animal[sounds.index(x)],input().split())))
0
Hi Suael, that's awesome!
Thanks for this answer. I would definitely try using Lambdas.