【问题标题】:How to tackle this Inverse Relation homework?如何解决这个逆关系作业?
【发布时间】:2016-08-16 20:20:00
【问题描述】:

这是我的任务:

编写一个函数inverse(rel),它接受关系rel 并返回关系rel 的逆关系。关系 R 的逆关系 InvsetR 定义为 InvsetR = {(x, y) ∈ S × S |(y, x) ∈ R)}。示例:

inRelation({(1,1), (1,2), (2,3), (4,2)}) 应该返回

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

这是我的代码:

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

它说我只能添加一个元素。我能做什么?

【问题讨论】:

  • 你应该像这样添加一对(y, x)m.add((y, x))
  • 你需要使用m.add((y,x))
  • m.add(x,y) 使用 两个 参数 xy 调用 add 函数。你需要传递一个参数:元组(x,y),所以你需要写m.add((x,y))
  • 非常感谢!它现在可以工作了.. 但不是 {(1,1), (2,1), (3,2), (2,4)} 它返回 {(3, 2), (1, 1), (2 , 4), (2, 1)}.. 为什么?我该怎么办?
  • @Margarita:在 Python 中,set 是唯一元素的无序集合。要获得有序列表,请使用:sorted(m)

标签: python set add relation inverse


【解决方案1】:

对于这个特定的示例,您不需要任何自定义函数,只需使用 python 已经提供的内置函数,几个示例:

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)

【讨论】:

    【解决方案2】:

    如果“关系”是一组 (x, y) 对:

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

    倒置关系是:

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

    inRelation 可以是:

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

    注意:我更喜欢蛇壳:inv_relation

    【讨论】:

      猜你喜欢
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多