小编vac*_*456的帖子

TypedDict 的 Python typehint 子集(部分)

在打字稿中,我们有Partial 类型,所以我们可以这样做:

interface Foo {
    x:number
    y:number
}

const foo:Partial<Foo> = {x: 1}
Run Code Online (Sandbox Code Playgroud)

(通过这个我们可以使接口的所有属性都是可选的)

在 Python 中,我们可以使用 来做到这一点total=False,如下所示:

from typing_extensions import TypedDict


class Foo(TypedDict, total=False):
    x:int
    y:int

foo:Foo = {'x':1}
Run Code Online (Sandbox Code Playgroud)

但这种方法不太好,因为这意味着 allFoo必须将所有属性尽可能为 None,并且我们需要进行大量类型转换。在 python 中,是否有一种方法可以声明 TypedDict,然后将其某些实现作为该类型的子集,如下所示:

from typing_extensions import TypedDict


class Foo(TypedDict):
    x: int
    y: int


foo:Partial[Foo] = {'x': 1}
Run Code Online (Sandbox Code Playgroud)

python type-hinting partial python-typing typeddict

14
推荐指数
1
解决办法
3145
查看次数

所有 O(n) 算法也是 O(n²) 吗?

大O记法的正式定义是,如果我们有一个函数f(n)(时间和算法的空间)和其他功能g(x),并有常数c,并no使得c*g(n) > f(x)所有n > no的话f(n) = O(g(n))。但是使用这个定义以及不断增长的二次函数总是会在某个时候超过线性函数的事实,所有O(n)函数都是真的O(n²)吗?或者更好地说,是n = O(n²)

algorithm complexity-theory big-o time-complexity space-complexity

3
推荐指数
1
解决办法
83
查看次数