I've been doing a lot of HackerRank challenges lately and many of them are in the form of "read instructions from input() and perform the instruction on an object." For example, with a list challenge, the instructions might be append, pop, etc.
A trick I have used before to make this sort thing more elegant is to use a dict to map strings to functions. E.g for foo()
and bar()
, {"foo":foo, "bar":bar}
and so on. There are more examples of this technique in this question.
What isn't clear to me is how to do this trick with member functions like append and pop and such.
What I want is for some list L, d['append']("foo")
=> L.append("foo")
.
I think you could just basically do the same thing you're already doing. Just add L.
to all the list class methods you need. Here is a minimal example:
L = []
d = {
'append': L.append,
'pop': L.pop
}
d['append']('foo') # equivalent to L.append('foo')
print(L) # prints ['foo']
d['pop']() #same thing
print(L) # prints []
The one drawback is you can only call these on the list L
. You would need to define other dictionary members (or other dictionaries) to operate on other lists.