Reputation: 1159
I have the following code:
N1 = int(input())
a = set(list(map(int, input().split())))
N2 = int(input())
for i in range(N2):
b = input().split()
c = set(list(map(int, input().split())))
a.b[0](c)
print(sum(a))
With typical input, the list b
looks like this:
b = ['intersection_update', '10']
What is the issue with a.b[0](c)
? Apparently I am not evaluating it correctly.
The concept seems fine, but it seems like set a
is not able to take an attribute which is actually an element of a list.
what I want to evaluate is:
a.intersection_update(c)
Here's the error I get:
Traceback (most recent call last):
File "solution.py", line 7, in
a.b[0](c)
AttributeError: 'set' object has no attribute 'b'
Upvotes: 0
Views: 2976
Reputation: 59118
You can't do that kind of indirect attribute access using the dot operator in Python. Use getattr()
instead:
>>> a = {1, 2, 3, 4, 5}
>>> c = {3, 4, 5, 6, 7}
>>> b = ['intersection_update', '10']
>>> getattr(a, b[0])(c)
>>> a
{3, 4, 5}
Upvotes: 1
Reputation: 104712
I think you want to use getattr
, to get an attribute who's name stored as a string in another variable:
getattr(a, b[0])(c)
Your current code is looking for an attribute named b
on the a
set.
Upvotes: 1