I recently began to learn programming. During a HackerRank problem solving session, this one came up:
You are given a set A and N number of other sets. These N number of sets have to perform some specific mutation operations on set A. Your task is to execute those operations and print the sum of elements from set A.
Here is a sample input (always in str format):
16 # number of elements on set A
1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52 # set A
4 # number of operations to realize on set A
intersection_update 10 # first input with operation and number of elements on the incoming set
2 3 5 6 8 9 1 4 7 11 # first set to realize operation on set A
update 2 # second input with operation and number of elements on the incoming set
55 66 # second set
The number of inputs is as big as N.
Here is my inefficient solution (1):
num_elem_a = int(input())
set_a = set(map(int, input().split()))
num_oper = int(input())
for i in range(0, num_oper):
entry = input().split()
if entry[0] == 'intersection_update':
set_a.intersection_update(set(map(int, input().split())))
elif entry[0] == 'update':
set_a.update(set(map(int, input().split())))
elif entry[0] == 'difference_update':
set_a.difference_update(set(map(int, input().split())))
elif entry[0] == 'symmetric_difference_update':
set_a.symmetric_difference_update(set(map(int, input().split())))
print(sum(set_a))
I am trying to learn how to code without all these "if's", and found a shorter and apparently cleverly solution (2):
(_, A) = (int(input()),set(map(int, input().split())))
B = int(input())
for _ in range(B):
(command, newSet) = (input().split()[0],set(map(int, input().split())))
getattr(A, command)(newSet)
print (sum(A))
Here is my doubt:
In my code (1) I had to call a method this way:
set_a.symmetric_difference_update(set(map(int, input().split())))
How is the getattr(A, command)(newSet)
line doing the same job in (2)? I don't get the logic.
I understood which elements the command is calling, but I don't see how this command produces the same effect as my version in (1).