Sets.symmetric_difference()|HackerRank Solutions

admin
By -
0
 This simple we just need to  read two sets items and them make their symmetric difference using function and then sort them ascending order which is default order and then print with or unpack each element of this  difference set  into separate lines  for this you  do not need to  write foo loop  you can use starred and sep="" to  do it but if  input size pretty huge then maybe this not works then you can use more efficient  ways 



finding the symmetric difference between two sets of integers. The symmetric difference of two sets is the set of elements that appear in either of the sets, but not in both. For example, if we have two sets A = {1, 2, 3} and B = {2, 3, 4}, the symmetric difference is {1, 4}.

Code:
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
s1 = set(map(int,input().split()))
m = int(input())
s2 = set(map(int,input().split()))
dif = sorted(s1.symmetric_difference(s2))
print(*dif, sep="\n")

'''
The code starts by reading an integer `n`, which represents the size of the first set.
Although the value of `n` is read,
it is not explicitly used in the logic of the code.

Next, the code reads a line of space-separated integers and
converts them into a set `s1`.
This set contains the unique integers from the first input,
ensuring that any duplicates are removed.

The same process is repeated for the second set `s2`,
where the code reads another integer `m`
representing the size of the second set (again, `m` is not used further in
the code),
and then a list of space-separated integers is converted into a set.

After both sets have been created,
the symmetric difference between `s1` and `s2` is calculated using the
`symmetric_difference()` method.
This operation finds all the elements that are present in either of the sets
but not in both.

The result of the symmetric difference is then sorted in
ascending order using the `sorted()` function.
This ensures that the elements are printed in a predictable order.

Finally, the code prints each element of the sorted symmetric difference
on a new line using the `print()` function.
The `*` operator is used
to unpack the sorted list and pass each element individually to `print()`,
with `sep="\n"` ensuring that each element is printed on a separate line.
'''

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*