#Stuck on a bit of python code

27 messages · Page 1 of 1 (latest)

desert forum
#

im doing this problem where you input the number of commands then input the commands and then the program runs it.

the answer was:

from collections import deque

d = deque()

for _ in range(int(input())):
    method, *n = input().split()
    getattr(d, method)(*n)

print(*d)

Im confused on how this for loop manages to run the commands inputted. Can anyone explain this ? Ex: you would input 1(3 of commands) and then append 1(commands) and then it would output the deque after the command: 1

magic pine
desert forum
#

it doesnt work tho

#

why is that

magic pine
#

Since method is a variable you can't do d.method. It won't evaluate your method variable it'll be trying to use a method d.method

#

When you do getattr(d, method) the method gets evaluated and replaced with the string from your user input

#

getattr(d, "user_input") like that
@desert forum

#

I guess more correctly d.method(*n) is the equivalent of getattr(d, "method")(*n)

desert forum
#

can you give an example of what would happen if *n = 1 and method = append ?

#

i just dont understand how it works in general

magic pine
#

getattr(d, "append")(1)

Which is equivalent to d.append(1)

#

getattr(d, "append") will return d.append

desert forum
#

and then it treats that as a line of code to be executed ?

magic pine
#

All lines of code are executed 🙂

desert forum
#

so

#

getattr(d, method)(*n) = d.append(1)

#

in that situation

magic pine
#

Yeah

#

You just need to use getattr vs dot notation because you are getting the method from user input

desert forum
#

ok

#

that makes so much more sense

#

ty so much

#

i was so cofnused

magic pine
#

Np

desert forum
#

should i close this or something ?

magic pine
#

You can, I'm not 100% sure how forums work tbh haha, I think it might close itself eventually?