I am kind of new to Python. I saw the following code and do not understand how a "list" can be used for sorting a string.
lookup = defaultdict(list)
## Filling the lookup
# .....
# .....
inputs = ['abc', 'acb', 'acb'] # a list of strings
result = ''.join(sorted(inputs[0], key=lookup.get))
What I don't understand is the last line the key part. I know it does a lexicographical sort based on the values in the list. I appreciate it if someone can explain it or break this step down to a more readable solution.
for example, if the lookup table looks like this:
{'a' : [-3, 0, 0], 'b': [0, -1, -2], 'c': [0, -2, -1]}
then the result will be this acb
The key argument to sorted means "Pretend the value is the result of this function instead of the actual value." So when you sort 'abc' with the lookup table you gave, it does this:
# [1st, 2nd, 3rd] sort order
lookup.get('a') # [ -3, 0, 0]
lookup.get('b') # [ 0, -1, -2]
lookup.get('c') # [ 0, -2, -1]
Then it will figure out the sorted order of the above values. Lists are sorted lexicographically meaning the first element is compared first, just like in a dictionary ("aardvark" comes before "beaver" and also before "ant").
After looking at the first elements (-3, 0, 0) we know 'a' has the smallest value, but we don't know which of 'b' and 'c' is smaller. But as soon as we see the second elements (0, -1, -2), we know that 'c' is smaller, so the final order is 'acb' without ever consulting the third elements (0, -2, -1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With