Anonymous user
Symmetric difference: Difference between revisions
→{{header|Lua}}: Add object-oriented Lua version
m (→{{header|Python}}: Note about difference set operators and methods) |
(→{{header|Lua}}: Add object-oriented Lua version) |
||
Line 1,243:
print( b_a )
end</lang>
Object-oriented approach:
<lang lua>SetPrototype = {
union = function(self, other)
local res = Set{}
for k in pairs(self) do res[k] = true end
for k in pairs(other) do res[k] = true end
return res
end,
intersection = function(self, other)
local res = Set{}
for k in pairs(self) do res[k] = other[k] end
return res
end,
difference = function(self, other)
local res = Set{}
for k in pairs(self) do
if not other[k] then res[k] = true end
end
return res
end,
symmetric_difference = function(self, other)
return self:difference(other):union(other:difference(self))
end,
-- return string representation of set
tostring = function(self)
local l = {}
for e in pairs(self) do l[#l+1] = e end
return "{" .. table.concat(l, ", ") .. "}"
end,
-- print set
["print"] = function(self)
print(self:tostring())
end
}
function Set(items)
local _set = {}
setmetatable(_set, {__index = SetPrototype})
for _, item in ipairs(items) do _set[item] = true end
return _set
end
A = Set{"John", "Bob", "Mary", "Serena"}
B = Set{"Jim", "Mary", "John", "Bob"}
print "Set A:"
A:print()
print "\nSet B:"
A:print()
print "\nSymmetric difference (A \\ B) ∪ (B \\ A):"
A:symmetric_difference(B):print()
print "\nUnion A ∪ B:"
A:union(B):print()
print "\nIntersection A ∩ B:"
A:intersection(B):print()
print "\nDifference A \\ B:"
A:difference(B):print()
print "\nDifference B \\ A:"
B:difference(A):print()
</lang>
'''Output:'''
Set A:
{Mary, Serena, John, Bob}
Set B:
{Mary, Jim, John, Bob}
Symmetric difference (A \ B) ∪ (B \ A):
{Serena, Jim}
Union A ∪ B:
{John, Mary, Jim, Serena, Bob}
Intersection A ∩ B:
{Mary, John, Bob}
Difference A \ B:
{Serena}
Difference B \ A:
{Jim}
=={{header|Mathematica}}==
|