[Evans] There are many different ways we could solve this problem.
First we'll look at a way of solving it using a while loop.
We'll define our find_element procedure.
We'll use p as the name of the list and t as the name of the target,
the element that we want to match.
We'll define the loop to go through the elements of p,
similarly to the previous while loops we've seen that go through lists.
We have our while loop. We've introduced the variable i.
We'll use that as the index to go through the loop.
The stopping condition for the while loop is when i reaches the len(p),
so we want our test for the while loop to be i < len(p).
In the block of the while loop we want to check if the current element matches t,
so we get the current element using p[i] and then we use == to test if it's equal to t.
If we find a match, meaning the 2 values are equal,
then we want to return the index that we found.
So the result should be the value of i,
which is the index where we found the matching element.
The risky thing about using while loops instead of for-loops
is it's really easy to forget that you need to increase the index variable.
If we just left the loop like this, it would run forever
because the value of i would never change unless the first element matched,
in which case we would return 0.
The loop would just keep going on forever, again checking the first element.
So we need to increase the value of i,
and that's the end of the while block.
The way we described what the find_element procedure should do,
if the element was not found, it should return -1.
If we get to the end of the while loop without returning,
that means we've gone through the while loop for all values of i up to len(p) - 1.
We didn't find any element that matches, so we should return -1.
So that's one way to define find_element.
I'll also show you a way to define it using a for-loop.
The reason it's more natural to start thinking of defining find_element with a while loop
than a for-loop is because the value that we want to return from find_element
is the index itself.
When we use a for-loop with the standard syntax of going through the elements
of the loop, we don't keep track of the index.
We just see each element in order.
So we need to add something else to keep track of the index
because that's the value we want to return.
So we still need to use a variable to keep track of the index.
We'll use i as that variable just like we did in the while loop version.
Now instead of a while loop we'll have a for-loop.
We don't need to think of the stopping condition here
because it will just go through all the elements.
Similarly to the body of the while loop, we check if the current element is equal to t.
In the for-loop we can get the current element using the variable e.
That's what gets assigned each time we go through the loop body
to the value of the current element.
So our test is using == to compare e and t.
If they match, just like we did in the while version, we should return the result.
The result we want to return is the index where we found the match.
In the while version that was clear.
It made sense because we were looking at element p, index i.
In the version with the for-loop we have to be more careful to know where that index is.
We're using the variable i to keep track of that index, so we'll return i.
i starts at 0.
Each time through the loop we need to increase i
so we keep track of the current index as we go through the elements.
As with the previous definition, when we had the while loop,
if we got to the end without finding it, that meant that the element did not exist in p
and we should return -1.
We'll do the same thing here.
Ci sono diversi modi per risolvere questo problema.
Prima vediamo di risolverlo con 'while' .
Definiamo la nostra 'find_element' .
Usiamo 'p' come nome per la lista e 't' per il valore bersaglio,
l'elemento di cui cerchiamo la corrispondenza.
Definiamo il ciclo attraverso gli elementi di 'p' ,
come per i cicli 'while' che abbiamo già visto.
Abbiamo il nostro ciclo 'while' . Abbiamo introdotto la variabile 'i' .
La usiamo come indice per vedere a che punto siamo del ciclo.
La condizione che deve fermare il ciclo è quando 'i' raggiunge 'len(p)' .
quindi il test del nostro ciclo è 'i
Nel corpo del ciclo 'while' vogliamo vedere se l'elemento corrente è uguale a 't' ,
quindi esaminiamo l'elemento corrente usando 'p[i]' e poi '==' per vedere se corrispondono.
Se troviamo una corrispondenza, cioè se sono uguali,
vogliamo ritornare l'indice dell'elemento trovato.
Quindi il risultato dovrà essere il valroe di 'i' ,
che è l'indice dell'elemento trovato.
La parte rischiosa dell'usare 'while' invece di 'for'
è che è molto facile dimenticare di incrementare la variabile che rappresenta l'indice.
Se lasciassimo il ciclo così, girerebbe all'infinito
poiché il valore di 'i' non cambierebbe mai a meno di trovare il valore che cerchiamo alla posizione uno,
nel qual caso avremmo 0 come risultato.
Il ciclo continuerebbe ad andare per sempre, sempre controllando il primo elemento.
Incrementiamo quindi il valore di 'i' ,
e qui finisce il corpo di 'while'.
Il modo in cui abbiamo descritto 'find_element' dovrebbe funzionare,
se non troviamo elementi deve ritornare -1.
Se arriviamo al termine del ciclo senza interruzioni,
significa che abbiamo controllato tutti i valori di 'i' fino a 'len(p) -1' .
Non trovando elementi corrispondenti, ritorniamo -1.
Questo è un modo per definire 'find_element'.
Vi farò anche vedere come farlo con 'for'.
Viene più naturale cominciare a pensare questa procedura usando 'while'
poiché il valore che vogliamo ritornare
è proprio l'indice.
Usando 'for' per esaminare gli elementi
non teniamo traccia dell'indice.
Vediamo solo tutti gli elementi ordinati.
Quindi abbiamo bisogno di qualcos'altro per tenere traccia dell'indice
poiché è il valore che ci serve ritornare.
Abbiamo bisogno anche qui di una variabile per l'indice.
Usiamo 'i' come nel ciclo 'while'.
Adesso però usiamo un ciclo 'for'.
Non dobbiamo pensare alla condizione per fermare il ciclo
poiché terminerà finiti gli elementi della lista.
Come per 'while', controlliamo che l'elemento corrente sia uguale a 't' .
Nel ciclo 'for' l'elemento corrente ha nome 'e' .
Il nome viene assegnato ogni volta che eseguiamo il corpo del ciclo 'for'
al valore dell'elemento corrente.
Quindi il nostro test usa '==' per comparare 'e' e 't' .
Se corrispondono, come per 'while', ritorneremo il risultato.
Il risultato che vogliamo ritornare è l'indice dove abbiamo trovato la corrispondenza.
Nel ciclo 'while' è tutto più chiaro.
Aveva senso vedere l'elemento 'p' e l'indice 'i' .
Nella versione con 'for' dobbiamo essere più attenti per trovare l'indice.
Usiamo la variabile 'i' , quindi ritorniamo 'i'.
'i' comincia a '0'.
Ogni volta che c'è un giro del ciclo dobbiamo incrementare 'i' .
Teniamo così traccia dell'indice dell'elemento corrente.
Come nella procedura precedente, con 'while',
se arrivavamo alla fine senza trovare niente, significava che l'elemento corrispondente non c'era in 'p'
e dovevamo ritornare -1.
In questa procedura succede lo stesso.
この問題を解くことのできる方法はたくさんあります
まずwhileループを使用して
これを解く方法を見てみましょう
find_element関数を定義します
リストの名前としてp ターゲットの名前としてtを使い
一致させたい要素を使用します
以前学習したリストを処理する
whileループと同じように
pの要素を処理するループを定義します
whileループがあります 変数iを挿入しました
ループを実行するために
インデックスとしてそれを使用します
whileループの停止条件はiがlen(p)に達した時です
そのためwhileループのテストを
i<len(p)にする必要があります
whileループのブロックで現在の要素が
tと一致するかどうか調べ
p[ i ]を用いて現在の要素を取得し
ダブルイコールを使用してtと等しいかテストします
一致すると認められた場合は
2つの値が等しいということになり
見つけたインデックスを返します
結果はiの値になるはずです
これは一致する要素を見つけるインデックスです
forループの代わりにwhileループを使用する時に
気をつけることは
インデックスの変数を増やす必要があるのを
忘れがちになることです
このようにループをそのまま残したら
延々と実行されます
なぜなら1つ目の要素と一致しない限り
iの値が永遠に変わらないからです
この場合はゼロを返します
ループは延々と継続します
もう一度1つ目の要素を調べます
iの値を増やす必要があります
それはwhileブロックの終わりです
find_element関数で行うべきことを
解説した時のように
要素が見つからなければ-1を返します
返すことなくwhileループの終わりまできた場合
iのすべての値をlen(p)-1まで
whileループすることになります
一致する要素を見つけ出すことはできません
ですから-1を返します
これがfind_elementを定義する1つの方法です
forループを使用して定義する方法も紹介します
forループよりwhileループで
find_elementを定義することから考え始めるのが
より自然な理由はfind_elementから
返す必要のある値がインデックス自体だからです
ループの要素を処理する一般的な構文で
forループを使用した時
インデックスを追跡しません
順番にそれぞれの要素を見ていくだけです
つまりインデックスを追跡するために
他のものを追加する必要があります
なぜならそれが返す必要のある値だからです
インデックスを追跡する変数を
使用する必要があります
whileループで行ったように
その変数としてiを使用します
ここでwhileループの代わりにforループを置きます
すべての要素を1つ1つただ見ていくだけなので
停止条件を考える必要はありません
whileループ本体と同様に
現在の要素がtと等しいかどうか調べます
forループでは変数eを用いて現在の要素を取得します
これはループ本体を通過するたびに
現在の要素に代入されるものです
eとtを比較するために
ダブルイコールを使用してテストします
whileループで行ったように一致すれば結果を返します
返したい結果は一致すると分かったインデックスです
whileループではそれが明白でした
要素pとインデックスiを見るので
意味をなしていました
forループの場合はインデックスがどこにあるか
把握するためにもっと気をつけなくてはなりません
そのインデックスを追跡するために変数iを使用します
ですからiを返します
iはゼロで開始します
ループを終えるたびにiを増やす必要があります
要素を処理すると同時に
現在のインデックスを追跡します
以前の定義と同様にwhileループがある時
それを見つけ出すことなく終了する場合
要素がpに存在していないことになります
そして-1を返す必要があります
ここで同じことを行います
[Evans] 解决这个问题的方法有很多种。
首先,我们来看看使用while循环的解决方法。
我们将定义我们的find_element过程。
我们将用p作为列表的名字,用t作为目标的名字,
也就是我们想要匹配的元素。
我们将定义这个循环来遍历p中所有元素,
这跟我们之前见过的遍历列表的while循环相似。
我们有一个while循环。我们已经引入了变量i。
我们将用它作为索引来遍历循环。
while循环停止的条件是当i达到len(p),
所以我们要让while循环的测试为i < len(p)。
这个while循环的块中,我们要检查当前元素与t匹配,
于是我们使用p[i]得到当前元素,接着用==来测试它是否等于t。
如果我们找到一个匹配,即找到两个相等的值,
那么我们就要返回找到的索引。
所以结果应为i的值,
这就是我们找到匹配元素的索引。
相对于使用for循环,使用while循环的风险在于
你很容易忘记你需要增加所以变量。
如果我们把循环就这样放着,它会永无休止地运行,
因为如果找不到第一个匹配的元素,i的值就永远不变,
这样,我们就返回0。
这个循环会不停继续下去,再次检查第一个元素。
所以我们需要增加i的值,
这就是while循环块的结尾。
我们这样描述find_element过程应做什么,
如果找不到元素,过程应返回-1。
如果我们完成了while循环而没有返回,
这意味着我们已经遍历了while循环所有i的值直至达到len(p) - 1。
我们没有找到任何匹配的元素,所以我们应返回 -1。
这就是定义find_element过程的一种方法。
下面我将向你展示如何使用for循环来定义该过程。
我们开始思考定义find_element时会更自然地想到使用while循环
而不是for循环,是因为我们想从find_element返回的值
是索引本身。
当使用一个采用标准句法遍历循环中元素的for循环
我们不追踪索引。
我们看到的只有依次排列的各个元素。
所以我们需要添加一些内容来追踪索引,
因为索引是我们想要返回的值。
所以我们仍然需要使用一个变量来追踪索引。
我们将使用i作为变量,正如之前在while循环中的做法。
现在我们有一个for循环,而不是while循环。
在这里我们不需要考虑停止条件
因为它只会遍历所有元素。
与while循环正文相似,我们检查当前元素是否等于t。
在这个for循环中,我们可以通过使用变量e来得到当前元素。
每次我们遍历循环正文时,
当前元素就是这样被赋值的。
我们的测试是使用==来比较e和t。
正如我们之前的while循环的做法,如果它们匹配,我们应返回结果。
我们想要返回的结果是我们找到匹配的索引。
在之前的while循环中,这点已经明确了。
这很好理解,因为我们看的是元素p,索引i。
在for循环中,我们必须更加注意,要知道那个索引在哪里。
我们使用变量i来追踪那个索引,所以我们将返回i。
i从0开始。
每一次遍历循环我们都需要增加i。
所以,我们在遍历元素时追踪当前索引。
正如在之前的定义中,我们使用while循环,
如果到了结尾我们没有找到元素,那就意味着这个元素在p中不存在,
我们应返回 - 1。
在这个for循环中,我们同样这么做。
有很多不同的方法可以解決這個問題
首先,我們來看看使用 while loop 的方法
我們定義程序 find-element
我們使用 p 作為列表名稱, t 作為標靶 (target) 的名稱
也就是我們要比對的元素
我們定義 loop 來走遍 p 的元素
和之前走遍列表的 while loop 相似
我們有一個 while loop,引入變數 i
我們把它作為指標來走遍 loop
while loop 的停止條件是,當 i 達到 len(p)
所以 while loop 的測試為 i < len(p)
在 while loop 程式塊裡,
我們要檢查目前的元素是否與 t 相等
於是我們使用 p[i] 得到目前元素,
接著用 '==' 來測試它是否等於 t
如果我們找到符合的值,也就是這兩個的值相等
我們傳回找到的指標
所以結果應為 i 值
這就是我們找到相等元素的指標
相對於 for loop ,使用 while loop 的風險在於
很容易忘了增加指標變數
如果我們把 loop 就這樣放著,它會永無休止地執行
i 的值永遠不變,除非第一個元素符合
這種情況下,我們傳回 0
這個 loop 會不停地繼續下去,再次檢查第一個元素
所以我們必須增加 i 的值
這是 while 程式塊的結尾
我們這樣描述 find-element 程序應做的事
如果找不到元素,程序應傳回 -1
如果我們完成了 while loop 而沒有傳回任何值
這意謂著,我們已經走遍 while loop 所有 i 的值,
直到 len(p) - 1
我們沒有找到任何相等的元素,所以我們應傳回 -1
這是定義 find-element 程序的一種方法
我也要向你展示,使用 for loop 來定義它的方法
很自然地想用 while loop 來定義 find-element 的原因
是因為我們想從 find-element 傳回的值
是指標 (index) 本身
當我們以 for loop 標準語法走遍 loop 的元素時
並沒有追蹤指標
我們只看到依次排列的元素
所以我們需要加點內容來追蹤指標
因為指標是我們想要傳回的值
所以我們仍然需要一個變數來追蹤指標
我們使用 i 作為變數,如同 while loop 版本的做法
現在我們使用 for loop ,而不是 while loop
在這裡,我們不需要考慮停止條件
因為它只是走遍所有元素
與 while loop 程式塊相似,
我們檢查目前的元素是否等於 t
在 for loop 中,我們可以使用變數 e 得到目前的元素
每次我們走遍 loop 程式塊
目前元素的值就是這樣被指定的
我們的測試是使用 '==' 來比較 e 和 t
如同 while 版本,如果它們相等,我們應傳回結果
我們想要傳回的結果,是我們找到相等時的指標
在 while 版本中,已經很清楚了
這很合理,因為我們看到元素 p,指標 i
在 for loop 版本中,我們必須更加注意那個指標在哪裡
我們使用變數 i 來追蹤那個指標,所以我們傳回 i
i 從 0 開始
每經過一次 loop,都需要增加 i
當我們在走遍元素時,同時追蹤目前指標
如同之前的定義,當我們使用 while loop
如果到了結尾我們沒有找到元素,
那就意謂著這個元素在 p 中不存在
我們應傳回 -1
在這裡,我們做同樣的事情