簡體   English   中英

給定 python 中的關系,是否有一種標准方法可以將可互操作對象划分為等價類?

[英]Is there a standard way to partition an interable into equivalence classes given a relation in python?

假設我有一個有限的可迭代XX上的等價關系~ 我們可以定義一個 function my_relation(x1, x2)如果x1~x2則返回True ,否則返回False 我想編寫一個 function 將X划分為等價類。 也就是說, my_function(X, my_relation)應該返回~的等價類列表。

在 python 中有沒有標准的方法來做到這一點? 更好的是,是否有專門用於處理等價關系的模塊?

我在John Reid找到了這個Python配方 它是用Python 2編寫的,我將它改編為Python 3來測試它。 該配方包括一個測試,用於根據lambda x, y: (x - y) % 4 == 0的關系將整數集[-3,5)划分為等價類。

它似乎做你想要的。 這是我在Python 3中想要的改編版本:

def equivalence_partition(iterable, relation):
    """Partitions a set of objects into equivalence classes

    Args:
        iterable: collection of objects to be partitioned
        relation: equivalence relation. I.e. relation(o1,o2) evaluates to True
            if and only if o1 and o2 are equivalent

    Returns: classes, partitions
        classes: A sequence of sets. Each one is an equivalence class
        partitions: A dictionary mapping objects to equivalence classes
    """
    classes = []
    partitions = {}
    for o in iterable:  # for each object
        # find the class it is in
        found = False
        for c in classes:
            if relation(next(iter(c)), o):  # is it equivalent to this class?
                c.add(o)
                partitions[o] = c
                found = True
                break
        if not found:  # it is in a new class
            classes.append(set([o]))
            partitions[o] = classes[-1]
    return classes, partitions


def equivalence_enumeration(iterable, relation):
    """Partitions a set of objects into equivalence classes

    Same as equivalence_partition() but also numbers the classes.

    Args:
        iterable: collection of objects to be partitioned
        relation: equivalence relation. I.e. relation(o1,o2) evaluates to True
            if and only if o1 and o2 are equivalent

    Returns: classes, partitions, ids
        classes: A sequence of sets. Each one is an equivalence class
        partitions: A dictionary mapping objects to equivalence classes
        ids: A dictionary mapping objects to the indices of their equivalence classes
    """
    classes, partitions = equivalence_partition(iterable, relation)
    ids = {}
    for i, c in enumerate(classes):
        for o in c:
            ids[o] = i
    return classes, partitions, ids


def check_equivalence_partition(classes, partitions, relation):
    """Checks that a partition is consistent under the relationship"""
    for o, c in partitions.items():
        for _c in classes:
            assert (o in _c) ^ (not _c is c)
    for c1 in classes:
        for o1 in c1:
            for c2 in classes:
                for o2 in c2:
                    assert (c1 is c2) ^ (not relation(o1, o2))


def test_equivalence_partition():
    relation = lambda x, y: (x - y) % 4 == 0
    classes, partitions = equivalence_partition(
        range(-3, 5),
        relation
    )
    check_equivalence_partition(classes, partitions, relation)
    for c in classes: print(c)
    for o, c in partitions.items(): print(o, ':', c)


if __name__ == '__main__':
    test_equivalence_partition()

我不知道有任何python庫處理等價關系。

也許這個片段很有用:

def rel(x1, x2):
   return x1 % 5 == x2 % 5

data = range(18)
eqclasses = []

for x in data:
     for eqcls in eqclasses:
         if rel(x, eqcls[0]):
             # x is a member of this class
             eqcls.append(x)
             break
     else:
         # x belongs in a new class
         eqclasses.append([x])


eqclasses
=> [[0, 5, 10, 15], [1, 6, 11, 16], [2, 7, 12, 17], [3, 8, 13], [4, 9, 14]]
In [1]: def my_relation(x):
   ...:     return x % 3
   ...:

In [2]: from collections import defaultdict

In [3]: def partition(X, relation):
   ...:     d = defaultdict(list)
   ...:     for item in X:
   ...:         d[my_relation(item)].append(item)
   ...:     return d.values()
   ...:

In [4]: X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

In [5]: partition(X, my_relation)
Out[5]: [[3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]

對於二元函數:

from collections import defaultdict
from itertools import combinations

def partition_binary(Y, relation):
    d = defaultdict(list)
    for (a, b) in combinations(Y):
        l = d[my_relation(a, b)]
        l.append(a)
        l.append(b)
    return d.values()

你可以這樣做:

partition_binary(partition(X, rank), my_relation)

哦,如果my_relation返回一個布爾值,這顯然不起作用。 我想說出一些抽象的方式來表示每個同構,盡管我懷疑這是首先嘗試這樣做的目標。

以下函數采用可迭代的a和等價函數equiv ,並按您的要求執行:

def partition(a, equiv):
    partitions = [] # Found partitions
    for e in a: # Loop over each element
        found = False # Note it is not yet part of a know partition
        for p in partitions:
            if equiv(e, p[0]): # Found a partition for it!
                p.append(e)
                found = True
                break
        if not found: # Make a new partition for it.
            partitions.append([e])
    return partitions

例:

def equiv_(lhs, rhs):
    return lhs % 3 == rhs % 3

a_ = range(10)

>>> partition(a_, equiv_)
[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]

這會有用嗎?

def equivalence_partition(iterable, relation):
    classes = defaultdict(set)
    for element in iterable:
        for sample, known in classes.items():
            if relation(sample, element):
                known.add(element)
                break
        else:
            classes[element].add(element)
    return list(classes.values())

我嘗試過:

relation = lambda a, b: (a - b) % 2
equivalence_partition(range(4), relation)

返回的是:

[{0, 1, 3}, {2}]

編輯:如果您希望盡快運行,您可以:

  • 將它包裝在Cython模塊中(刪除defaultdict,沒有太多要改變的東西)
  • 想嘗試用PyPy運行它
  • 找到一個專用模塊(無法找到任何)

NetworkX 庫似乎內置了此功能 也許你可以使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM