So far, we've been doing--in our Phyton IDE--
we've been doing what are called sequential scans.
And a sequential scan is where you have a list of something.
In our case, links.
We have this list of links
that have these IDs--link 1, link 2, link 3.
And we've been doing things like find the link with the ID of 2,
so in which case we write a loop to
go over the list and find the one who has ID 2.
Or you just eyeball it by hand
and answer your quiz just by writing in the answer by hand,
which is actually totally fine because you went through the same process.
You had to look through this whole list of links by hand.
Now, that works fine if you have 25 links,
but if you have a million links or a billion links,
iterating over that entire list is going to take some time,
and we want to make our websites fast,
or at least reasonably responsive.
So that's going to be troublesome.
So I'd like to introduce you to a new concept called Indexes.
And index is just like an index in a book.
They make lookups faster.
One index you're probably familiar with already is the hashtable.
So in Python you can have a dictionary
that looks something like this--
that is a mapping--a key--to a value.
Let's assign this to a variable.
We'll call this just index.
Now, you can do very fast lookups in your code
by writing something that looks like this,
which we'll refer to the index key 2 of this hash table.
And when you do a hashtable lookup--
you learned this in CS 101--
we hash this value, we find it in the hashtable,
and then we return the key--
or we return the value.
We don't have to scan over every element in the list and see if it matches our constraint.
We can jump immediately to that element.
And that makes queries run much faster.
Okay, so let's play around with this in the IDE a little bit
and see what we can do.
Hasta ahora, en nuestro Phyton IDE,
hemos hecho lo que se llama "sequential scans".
Un sequential scan es donde tienes una lista de algo.
En nuestro caso, de links.
Tenemos esta lista de links
que tienen estos ID: link 1, link 2, link 3.
Hemos hecho cosas como buscar el link con el ID 2,
en cuyo caso escribimos una trayectoria
para repasar la lista y encontrar al que tiene el ID 2.
O simplemente la repasas tú mismo
y responde al cuestionario para escribir la respuesta a mano,
lo que está bien ya que haces el mismo proceso.
Miras toda la lista tú.
Eso funciona si tienes 25 links,
pero si tienes un millón o mil millones de links,
observar toda la lista te va a llevar un tiempo
y lo que queremos es que nuestras páginas sean rápidas,
o, al menos, receptiva.
Así que eso será un problema.
Me gustaría presentarte un nuevo concepto: índices.
Un índice es como un índice de un libro.
Hacen que las búsquedas sean más rápidas.
Uno que probablemente conozcas es la tabla hash.
En Python puedes tener un diccionario
que se parezca a esto.
Esto es una conexión entre una llave y un valor.
Asignémosle esto a una variable.
Llamaremos a esto "index".
Puedes hacer muchas búsquedas rápidas en tu código
escribiendo algo que se parezca a esto,
donde nos referiremos a la llave 2 de la tabla hash.
Cuando haces una búsqueda en la tabla hash,
aprendiste esto en CS 101,
repasamos este valor, lo encontramos en la tabla hash
y devolvemos la llave,
o devolemos el valor.
No tenemos que buscar cada elemento en la lista y ver que encaja con nuestro requisito.
Podemos pasar directamente a ese elemento.
Eso hace que las consultas vayan mucho más rápido.
Juguemos un poco con esto en el IDE
y veamos qué podemos hacer.
これまではPython IDEで
シーケンシャルスキャンをしてきました
シーケンシャルスキャンは配列上で行います
このレッスンでは配列のリストですね
それぞれlink 1、link 2、link 3などの
IDがついています
これまでは特定のIDを持つリンクを探すために
ループ処理をしてリスト全体を検索していました
もしくは皆さんは目視で探して
小テストにも手書きで答えられたと思います
そのやり方には特に問題はありません
でも全リストのリンクを
目視で確認することになりますね
リンクが25個なら問題ありませんが
何百行ものリンクが格納されている場合は
手動で全リストを確認するのは非常に困難です
またWebサイトにはある程度の速さも欲しいので
手動では限界があります
そこでインデックスと呼ばれるデータ構造を使います
本の索引と同じようなもので
検索をスピードアップできます
ハッシュテーブルを例に挙げてみましょう
Python内には辞書を格納できます
これはキーと値をマッピングしたものです
変数にアサインしてみましょう
インデックスと名づけます
これにより検索のスピードが格段に向上します
先にハッシュテーブルの
インデックスにあるキーを確認するからです
ハッシュ関数を実行すると
ハッシュテーブルを検索して値をハッシュします
そしてキーもしくは値を返すのです
これで全リストをスキャンする必要がなくなりますね
エレメントに直接飛べるので
検索のスピードも格段に上がります
それではIDE上で実装しながら
使い方を学びましょう
Até agora, nós vimos - no nosso IDE Python -
fazendo algo chamado varreduras sequenciais.
E uma varredura sequencial acontece quando você tem uma lista de coisas.
No nosso caso, de links.
Nós temos esta lista de links
que têm esses identificadores (IDs) - link 1, link 2, link 3.
E nós vimos fazendo coisas como encontrar o link com a ID 2,
sendo que neste caso escrevemos um laço para
rever a lista, e encontrar o que tem a ID 2.
Ou você, simplesmente, dá uma averiguada "à mão" mesmo,
e responda o seu quiz escrevendo a resposta à mão,
o que não tem problema, porque você efetivamente realizou o mesmo processo.
Você teve que rever a lista de links à mão.
Agora, isto funciona bem se você tem 25 links,
mas se você tem um milhão de links, ou um bilhão de links,
fazer a iteração desta lista inteira vai tomar algum tempo,
e nós queremos construir websites rápidos,
ou que tenha, pelo menos, um tempo de resposta razoável.
Então, isto será preocupante.
Então, eu gostaria de introduzir um conceito novo chamado de Indexações.
Uma indexação é simplesmente como um índice em um livro.
Eles tornam as buscas mais rápidas.
Uma indexação com a qual você provavelmente já está familiarizado é a hashtable.
Então, em Python você pode ter um dicionário
que parece um pouco com isso -
que é um mapeamento - uma chave - para um valor.
Vamos atribuir isto a uma variável.
Nós vamos chamar isto apenas de índice.
Agora, você pode fazer buscas muito rápidas no seu código
ao escrever algo que se parece com isto,
ao que vamos nos referir como chave índice 2 da tabela hash.
E quando você faz uma busca na hashtable -
você aprendeu isso em CS 101 -
nós "esmiuçamos" este valor, o encontramos na hashtable,
e então retornamos sua chave -
ou retornamos seu valor.
Nós não temos que rever todos os elementos da lista e verificar se são compatíveis com nossos parâmetros.
Nós podemos pular diretamente para aquele elemento.
E isso faz com que as buscas sejam realizadas muito mais rápido.
Ok, então vamos brincar um pouco com isto no IDE
e ver o que podemos fazer.