-1

Here is my assignment:

Write a function inverse(rel) that takes a relation rel and returns the inverse relation of the relation rel. The inverse relation InvsetR of the relation R is dened as InvsetR = {(x, y) ∈ S × S |(y, x) ∈ R)}. Example:

inRelation({(1,1), (1,2), (2,3), (4,2)}) should return

{(1,1), (2,1), (3,2), (2,4)}

Here is my code:

def inverse(rel):
   m=set()
   for (x,y) in rel: 
      m.add(y,x)
   return m

It says that I can add only one element. What can I do?

halfer
  • 19,824
  • 17
  • 99
  • 186
Margarita
  • 7
  • 2

2 Answers2

0

For this particular example, you don't need any custom function of yours, just use the builtins python already provides, a couple of examples:

foo = set([(1, 1), (1, 2), (2, 3), (4, 2)])
inv_foo1 = map(lambda (a, b): (b, a), foo)
inv_foo2 = {(b, a) for (a, b) in foo}
print(foo)
print(inv_foo1)
print(inv_foo2)
BPL
  • 9,632
  • 9
  • 59
  • 117
0

If a "relation" is a set of (x, y) couples:

>>> relation = {(1,1), (1,2), (2,3), (4,2)}

The inverted relation is:

>>> inverted = {(y, x) for x, y in relation}
>>> inverted
{(3, 2), (1, 1), (2, 4), (2, 1)}

The inRelation can be:

def inRelation(relation):
    return {(y, x) for x, y in relation}

note: I prefer snake case: inv_relation

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103