Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
You don't necessarily have to loop through and initialize each key for strngs manually. Here's a couple of alternatives.
# Your versionstrngs={}forcharininitchar:strngs[char]=0# you can create a dict out of a sequence of keys and starting value# credit: @edh_developerstrngs=dict.fromkeys(initchar,0)# you can also use a defaultdict, which creates the key with a default value# if it doesn't find the key there on accessfromcollectionsimportdefaultdictstrngs=defaultdict(int)# defaults to zero
You can use shorthand notation if you're modifying a value inplace.
# Your versionstrngs[char]=strngs[char]+1# shortcutstrngs[char]+=1
You can use dict.items to get a list of pairs out of a dict that is much easier to sort. Then you don't have to manually sort and delete items out of your dict.
# Your versionwhile(strngs!={}):maximum=max(strngs,key=strngs.get)word=word+maximumdelstrngs[maximum]# Could bepairs=strngs.items()desc=sorted(pairs,key=lambdax:x[1])# the key= argument lets us# sort by the second itemdesc_letters=''.join(x[0]forxindesc)# Grab the first value (letter) from each pair
In general, when you're building a string, it's usually more performant, easier, and less error prone to build the whole thing as a list and join it at the end.
# Instead of this:word=""foriteminthings:word=word+complicated_process(item)# Since strings are immutable, this forces you to throw away# your old string and create a new one *each time* which is expensive# More efficient:word=[]foriteminthings:word.append(complicated_process(item))letters=''.join(word)# Use list comprehensions (see link below) for even faster,# cleaner, more pythonic code :)word=[complicated_process(item)foriteminthings]letters=''.join(word)# Use a generator expression (like above) for *even better* results!letters=''.join(complicated_process(item)foriteminthings)
Hi! A couple of notes that you can take or leave.
You don't necessarily have to loop through and initialize each key for
strngs
manually. Here's a couple of alternatives.You can use shorthand notation if you're modifying a value inplace.
You can use
dict.items
to get a list of pairs out of a dict that is much easier to sort. Then you don't have to manually sort and delete items out of your dict.Some things to look up here for more information:
In general, when you're building a string, it's usually more performant, easier, and less error prone to build the whole thing as a list and
join
it at the end.Here's a link on list comprehensions
Hopefully this helps. I'm not sure how comfortable you are with Python, so I tried to cover everything. Let me know if you have any questions 😁