0

HackerRank: Set .symmetric_difference() Operation

In conjuction with using SoloLearn, I'm also using HackerRank and a book published by O'Reilly Media to learn Python. A challenge on HackerRank's site asks to produce "8" when the following input is entered: 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 No commas, just how it looks. The code I came up with below has posed some interesting (and frustrating) challenges. When I first wrote, I used the symmetric difference operator "^" to get the answer, but I kept getting "4" and not "8." When I switched to the intersection operator "&" to get the answer, I got an "8." I thought this was it, but when I enter the code into HackerRank, it instead produces a "7," and closer inspection has led me to realize this code would fail multiple tests. Does anyone have any idea why any of this is happening to my code? As always, thanks in advance. eng_sub = int(input()) eng_sub_addresses = set(input()) french_sub = int(input()) french_sub_addresses = set(input()) diff = (eng_sub_addresses ^ french_sub_addresses) print(len(diff))

18th Apr 2020, 4:22 AM
deepspaceghost
deepspaceghost - avatar
3 odpowiedzi
+ 1
By directly converting the input to a set, the set will contain all characters of the input string as (unique) single characters. So we lose '55', only '5' will be in the set. Also the space character will be in the set.
18th Apr 2020, 5:47 AM
Lisa
Lisa - avatar
+ 1
Not sure (hardly ever used sets), but I suppose symmetric_difference() is designed for set comparisons. Probably you could find similar methods in math or science modules that operate on other object types. But I see no reason to avoid sets in your example. Did you solve the task using the sets?
20th Apr 2020, 4:10 PM
Lisa
Lisa - avatar
0
Lisa Thank you for the assist. Is there any way to accomplish .symmetric_difference() without using sets?
20th Apr 2020, 3:36 PM
deepspaceghost
deepspaceghost - avatar