在python3.10中尝试使用泛型时获得错误输出

uqxowvwt  于 2023-05-19  发布在  Python
关注(0)|答案(1)|浏览(141)

下面是我的代码:

from typing import (
    TypeVar,
    Iterable,
    Generic,
    Callable,
    Deque,
    Any,
    Optional,
    Protocol,
    Sequence,
)
from heapq import heappush, heappop

T = TypeVar("T")

def linear_contains(iterable: Iterable[T], key: T) -> bool:
    for item in iterable:
        if item == key:
            return True
        return False

C = TypeVar("C", bound="Comparable")

class Comparable(Protocol):
    def __eq__(self, other: Any) -> bool:
        ...

    def __lt__(self: C, other: C) -> bool:
        ...

    def __gt__(self: C, other: C) -> bool:
        return (not self < other) and self != other

    def __le__(self: C, other: C) -> bool:
        return self < other and self == other

    def __ge__(self: C, other: C) -> bool:
        return not self < other

def binary_contains(sequence: Sequence[C], key: C) -> bool:
    low: int = 0
    high: int = len(sequence) - 1
    while low < high:
        mid = (low + high) // 2
        if sequence[mid] < key:
            low = mid + 1
        elif sequence[mid] > key:
            high = mid - 1
        else:
            return True
    return False

if __name__ == "__main__":
    print(linear_contains([1, 4, 5, 23, 23, 23, 30], 5))
    print(binary_contains(["a", "d", "e", "f", "x", "z"], "f"))
    print(binary_contains(["john", "maek", "ronald", "sarah"], "sheila"))

预期输出为

True
True
False

但我得到了

False
False
False

有人能解释一下为什么会这样吗?
PS:这段代码摘自Python中的经典CS问题(here)。它是为python3.7编写的,但我想让它在python3.10中运行。我知道python中的typing有很多变化,但我在理解它(特别是泛型)方面遇到了一些问题。这就是为什么我们从这个代码开始。

fcg9iug3

fcg9iug31#

你的问题与打字无关。下面是从您提供的link中直接复制和粘贴的两个函数的代码。
你能看出这个版本和你用的版本有什么区别吗?如果评论中有任何问题,请随时提出后续问题。

def linear_contains(iterable: Iterable[T], key: T) -> bool:
    for item in iterable:
        if item == key:
            return True
    return False
def binary_contains(sequence: Sequence[C], key: C) -> bool:
    low: int = 0
    high: int = len(sequence) - 1
    while low <= high:  # while there is still a search space
        mid: int = (low + high) // 2
        if sequence[mid] < key:
            low = mid + 1
        elif sequence[mid] > key:
            high = mid - 1
        else:
            return True
    return False

相关问题