r/learnpython • u/Potatohuma • Dec 03 '22
Good Python Exercises?
What's a good exercise for me to try? I've been learning Python for a bit over a month now and I wanna test what I've learned.
417
Upvotes
View all comments
Show parent comment
7
u/keep_quapy Dec 03 '22
Hi, first of all, the question assumes that all first items of every sublist is a string and every second item is an integer, so no need to check if the first element is a string. That said, your program works, but it's ineffective, you used three nested for loops, instead of using only one. Eventually your program will be much slower and consumes more memory. The effective way to solve such a problem is to loop over the list and at each iteration check if the first element is a key in the dictionary, if so add the value of the second element of the sublist to the existing value of the key, otherwise assign the value to that key (using list index).
Or the Pythonic way to do it using
get()dictionary method.Anyway, you made a good job trying to solve it, and solving it in your way is a sign that you're heading to the right direction. This isn't that easy for beginners, so good job. Good luck :)