python - How to run different methods on strings through a variable? -


the question asks me create empty list , follow commands down input. first line tells me how many commands there in total followed said commands.

here sample input:

12             # number of commands insert 0 5     # l = [5] (insert 5 in position 0) insert 1 10    # l = [5, 10] (insert 10 in position 1) insert 0 6     # l = [6, 5, 10] (insert 6 in position 0) print          # print [6, 5, 10] remove 6       # l = [5, 10] append 9       # l = [5, 10, 9] append 1       # l = [5, 10, 9, 1] sort           # l = [1, 5, 9, 10] print          # print [1, 5, 9, 10] pop            # l = [1, 5, 9] reverse        # l = [9, 5, 1] print          # print [9, 5, 1] 

so output is:

[6, 5, 10] [1, 5, 9, 10] [9, 5, 1] 

here current code:

list = []     count = int(input()) z in range(0, count):     command = input().split()     if len(command) 1:         command(list)     elif len(command) 2:         list.command[0](command[1])     else:         list.insert(int(command[1]), int(command[2])) 

i have error of attributeerror: 'list' object has no attribute 'command'

i'm attempting use string in command[0] can insert, remove, append (or command if print, sort, or reverse) python literally taking term 'command' instead of string holding in memory, there way around without making if/else statements every single method case?

command not magically become right function or attribute, no.

you use getattr() attribute object:

command = (insert, 0, 5) getattr(list, command[0])(*command[1:]) 

but that'll cumbersome need keep testing how many arguments have , handle print case separately.

better use dictionary mapping commands functions:

commands = {     'print': lambda: print(list),     'insert': lambda pos, value: list.insert(pos, value),     # etc. } 

then call command via dictionary lookup, applying remaining values arguments:

commands[command[0]](*command[1:]) 

you insert bound methods; list.pop , list.insert take right arguments after all.

note want avoid list variable name, really. use stack perhaps. using python 3, can use catch-all target when assigning, letting split out command , arguments in 1 step:

stack = [] commands = {     'print': lambda: print(stack),     'insert': stack.insert,     'pop': stack.pop,     'remove': stack.remove,     'append': stack.append,     'sort': stack.sort,     'reverse': stack.reverse, }  count = int(input()) z in range(count):     command, *args = input().split()     commands[command[0]](*args) 

Comments