5.2. 搜索¶
5.2. Searching
现在,我们将注意力转向计算中最常见的一些问题——搜索和排序。在本节中,我们将学习搜索。排序的问题我们将在本章稍后讨论。搜索是指在一组项目中寻找特定项目的算法过程。搜索通常在查询某个项目是否存在时返回“True”或“False”。有时,搜索可以修改为返回找到该项目的位置。对于我们目前的目的,我们只关心成员资格的问题。
在 Python 中,有一种非常简单的方法可以判断某个项目是否在一组项目中。我们可以使用 in
运算符。
>>> 15 in [3, 5, 2, 4, 1]
False
>>> 3 in [3, 5, 2, 4, 1]
True
>>>
虽然这很容易编写,但在回答这个问题之前必须执行一个底层的过程。事实证明,有许多不同的方法可以搜索某个项目。我们感兴趣的是这些算法是如何工作的,以及它们彼此之间的比较。
We will now turn our attention to some of the most common problems that arise in computing, those of searching and sorting. In this section we will study searching. We will return to sorting later in the chapter. Searching is the algorithmic process of finding a particular item in a collection of items. A search typically returns either True
or False
when queried on whether an item is present. On occasion a search may be modified to return where the item is found. For our purposes here, we will simply concern ourselves with the question of membership.
In Python, there is a very easy way to ask whether an item is in a list of items. We use the in
operator.
>>> 15 in [3, 5, 2, 4, 1]
False
>>> 3 in [3, 5, 2, 4, 1]
True
>>>
Even though this is easy to write, an underlying process must be carried out to answer the question. It turns out that there are many different ways to search for the item. What we are interested in here is how these algorithms work and how they compare to one another.
创建日期: 2024年9月9日