Hi,
So I was doing a code challenge and it's about sorting a string in numerical order based on the integer as part of the string, e.g:
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
I did it by creating a list with placeholder values and then assigned the values based on the number identified, see:
def order(sentence):
temp = sentence.split()
result = [0 for x in range(len(temp))]
for item in temp:
for char in item:
if char.isnumeric():
num = int(char)
result[num-1] = item
return " ".join(result)I was just looking at other solutions and saw this cool one liner:
return sorted(temp, key=lambda w:sorted(w))
But I don't quite understand how it works :(
I have used the key= argument in the past, for example sorting by the size of the string, i.e key=len
The lambda uses a variable, w and passes it through sorted, but how does that sort by the number included in the string?
Yes, that's perfectly valid. You could for instance use it to store a counter to how many times a function was called:
def hi():
print('hi')
funcs = {hi: 0}
print(funcs)
# {<function hi at 0x10fb39950>: 0}
for func in funcs:
func()
# hi
funcs[func] += 1
print(funcs)
# {<function hi at 0x10fb39950>: 1}
Functions are represented through instance of function class:
>>> def f():
... pass
...
>>> f
<function f at 0x000001D397363E18>
>>> help(type(f))
class function(object)
| function(code, globals[, name[, argdefs[, closure]]])
So the function class is derived from object class and inherits __hash__ method. The default implementation of __hash__ method in object class computes hash using return value of id() by rotating right 4 bits. The id() of object is memory address.
So that's how functions get hash. Anything that has some immutable state can technically have hash.
Hi there, I was learning about the lambda/anonymous functions. And I came across this example which sorts a list:
lst = ["Mouse Keyboard", "Router Hub", "CPU UPS"]
lst.sort(key = lambda each: each.split(" ")[-1].lower())
print(lst)
# Which returns output:-
# ['Router Hub', 'Mouse Keyboard', 'CPU UPS']
I tried to google this but was not successful enough. If someone kindly enlightens me on what the key in the sort() function is for. With the google search, I concluded that it takes a function as input. So, the input here will be the 2nd word of each item in the list. But I'm unable to figure out how the sorting function is performed.