+ 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

8th Aug 2020, 2:29 PM
aejaz ayaz
aejaz ayaz - avatar
4 ответов
+ 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").
8th Aug 2020, 2:47 PM
Sandra Meyer
Sandra Meyer - avatar
+ 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!
8th Aug 2020, 4:28 PM
aejaz ayaz
aejaz ayaz - avatar
+ 1
sounds=['Grr','Rawr','Ssss','Chirp'] animal=['Lion', 'Tiger','Snake','Bird'] print(' '.join(map(lambda x:animal[sounds.index(x)],input().split())))
9th Aug 2020, 3:51 PM
Suhail KM
0
Hi Suael, that's awesome! Thanks for this answer. I would definitely try using Lambdas.
16th Aug 2020, 9:05 AM
aejaz ayaz
aejaz ayaz - avatar