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])
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
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
谈到习语python:我不认为python真的是一种数学语言(比如说,与Wolfram的mathematica相比),所以我们没有内置图像、映射等概念。然而,你可以看到我的代码上面的列表理解。事实上,我只是更明确地使用了set关键字,就像在set([function(x) for x in preimage])中一样,但是您可以用{function(x) for x in preimage}保存一些击键。你知道吗
假设TypeVar and other things from pep484
如果没有类型注释
或者是密码域的一个子集
对于从一个集合到另一个集合的任意图像,我将使用Python字典。例如,在{1,2,3,4}集合上,f(n)=n^2,我可以这样做:
当然,只有当你的有限集对于你的内存来说是有限的时,这才有效。你知道吗
以上是将函数定义为映射的最常见的情况。但对于更简单的函数,可以使用Python表达式来表示它,可以跳过字典:
如果进一步,你有一个反函数可用于域:
注意,上面三个不同的代码片段,只有第一个可以保证您的
function(x)
只允许预定义的前映像中的那些x
。你知道吗谈到习语python:我不认为python真的是一种数学语言(比如说,与Wolfram的mathematica相比),所以我们没有内置图像、映射等概念。然而,你可以看到我的代码上面的列表理解。事实上,我只是更明确地使用了
set
关键字,就像在set([function(x) for x in preimage])
中一样,但是您可以用{function(x) for x in preimage}
保存一些击键。你知道吗相关问题 更多 >
编程相关推荐