用于有限函数的有限集、图像和前图像的惯用Python实现?

2024-03-29 08:08:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设在有限集合之间有一个有限的具体函数。当然,Python已经在本地实现了set。你知道吗

但要实现集合间有限函数的概念,最好的方法是什么呢?包装好的字典?另外,如何实现图像和前图像的计算?[见下文。]

对于图像,我可以使用地图,很明显。对于预映像,我可以在域集上循环并过滤。不过,我还是想知道一个更为通俗易懂的解决方案。你知道吗

Wikipedia: Images (mathematics)


Tags: 方法函数图像概念字典地图wikipedia解决方案
2条回答
def preimage(b: B, f: Dict[A, B]) -> Set[A]: 
    ''' get the preimage of one item. '''
    return set(a for a in f.keys() if f[a]==b)

假设TypeVar and other things from pep484

from typing import TypeVar, Dict, Set
A = TypeVar('A')
B = TypeVar('B')

如果没有类型注释

def preimage(b, f): 
  ...

或者是密码域的一个子集

from typing import Collection
from functools import reduce

def preimage_(bs: Collection[B], f: Dict[A, B]) -> Set[A]: 
    ''' get the preimage of a collection of items '''
    return reduce(lambda a, b: a.union(b), [preimage(b, f) for b in bs])

对于从一个集合到另一个集合的任意图像,我将使用Python字典。例如,在{1,2,3,4}集合上,f(n)=n^2,我可以这样做:

preimage = set([1,2,3,4])
mapping = {x: x*x for x in preimage}
image = set(mapping.values())
assert set(mapping.keys()) == preimage
function = lambda x: mapping[x] # so you can now have y = function(x)
check_image = set([function(x) for x in preimage])
assert check_image == image

当然,只有当你的有限集对于你的内存来说是有限的时,这才有效。你知道吗

以上是将函数定义为映射的最常见的情况。但对于更简单的函数,可以使用Python表达式来表示它,可以跳过字典:

preimage = set([1,2,3,4])
function = lambda x: x*x
image = set([function(x) for x in preimage])
check_preimage = set([y for x in image for y in preimage if function(y)==x])
assert check_preimage == preimage

如果进一步,你有一个反函数可用于域:

import math
preimage = set([1,2,3,4])
function = lambda x: x*x
inv_func = lambda x: int(math.sqrt(x))
image = set([function(x) for x in preimage])
check_preimage = set([inv_func(x) for x in image])
assert check_preimage == preimage

注意,上面三个不同的代码片段,只有第一个可以保证您的function(x)只允许预定义的前映像中的那些x。你知道吗

谈到习语python:我不认为python真的是一种数学语言(比如说,与Wolfram的mathematica相比),所以我们没有内置图像、映射等概念。然而,你可以看到我的代码上面的列表理解。事实上,我只是更明确地使用了set关键字,就像在set([function(x) for x in preimage])中一样,但是您可以用{function(x) for x in preimage}保存一些击键。你知道吗

相关问题 更多 >