-1
I’m doing an exercise that asks to, given two sets, print in ascending order (line by line) the symmetric difference between them, my code:
n = set(input().split())
m = set(input().split())
m_diff = m.difference(n)
n_diff = n.difference(m)
result = [m_diff, n_diff]
if __name__ == '__main__':
for i in range(0, len(result)):
print(result[i])
input:
2 4 5 9
2 4 11 12
my output:
{'11', '12'}
{'9', '5'}
expected output:
5
9
11
12
How do I get the elements out of the sets and make them all become elements of just one list?
It didn’t happen because you put it like this
result = [m_diff, n_diff]
? Because there was not even the question of turning into a set, it was simply that took the "diffs" and placed one at index 0 and another at index 1, all knowing that the.difference
returns all results that differ in a newset
, well, if you want to put it all together the right way.union
(I guess I’m not sure) or the.update
or the "pipe" (set1|set2
)– Guilherme Nascimento
the problem that Difference() returns a set, I put on a list to give . Sort() and print item by item in ascending order, equal appears in expected output
– Pirategull
I said at the beginning, the problem doesn’t look like the rest of the code or Difference, it looks like
result = [m_diff, n_diff]
, I’m gonna use a[...,...]
when maybe you should have used Union or update, depending on what you want– Guilherme Nascimento
You were right, with the update returns the full set {'4', '12', '9', '11'}, now how do I print each element of the set?
– Pirategull
Take the set that was updated, after all this is different from . update() pro . Union(), right? I don’t remember exactly. If you used the update one of your sets has been updated, then one of them has all values
– Guilherme Nascimento
yes, update() has turned everything into a single set, with all the elements that interested me, but you cannot iterate and print as a list, nor use Sort(). I still have to know how to return the expected output
– Pirategull
Is not iterating the
set
? I guess you just usefor i in m_diff
orfor i in n_diff
(depending on which received the update)– Guilherme Nascimento
Iterating using the index is not the most idiomatic way to iterate on
Python
. The way proposed by @Guilhermenascimento, however, withfor var in iterable
is the most idiomatic and allows iterating in several ways– Jefferson Quesado
Thanks for the help, your method didn’t need to be made into a list, I didn’t know you could iterate there. Anyway, I will answer the question by converting the set into a list first.
– Pirategull