Searching & max / min
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
English
Linear search
- A linear search looks at each item in turn until it finds the target.
- It is a named standard method in the syllabus.
- Use a loop and remember when you find a match.
日本語
線形探索
- 線形探索は、ターゲットが見つかるまで各アイテムを順に確認します。
- これはカリキュラムにおける名付けられた標準手法です。
- ループを使用し、一致を見つけたときを記憶しておきます。
nums = [4, 9, 2, 7]
target = 9
found = False
for n in nums:
if n == target:
found = True
print(found) # True
Explore · 探索
Linear search, step by step
A linear search checks each item in turn until it finds the target.
English
Finding the maximum
- Start by assuming the first item is the biggest.
- Then check the rest; if one is bigger, remember it instead.
日本語
最大値を見つける
- まず最初のアイテムが最大だと仮定します。
- その後残りを確認し、より大きいものが見つかればそれを記憶します。
nums = [4, 9, 2, 7]
biggest = nums[0]
for n in nums:
if n > biggest:
biggest = n
print(biggest) # 9
English
Finding the minimum
- The same idea, but keep the smallest value seen so far.
日本語
最小値の探索
- 同じアイデアだが、これまでに見た最小値を保持する。
nums = [4, 9, 2, 7]
smallest = nums[0]
for n in nums:
if n < smallest:
smallest = n
print(smallest) # 2
English
In the exam: standard methods
- Linear search and finding maximum / minimum / average are named in section 7.
日本語
試験対策: 標準的な手法
- リニア検索と最大値・最小値・平均値の探索はセクション7で言及されている。
Found ← FALSE
FOR I ← 1 TO 4
IF Number[I] = Target
THEN
Found ← TRUE
ENDIF
NEXT I
English
Common mistakes
- Linear search checks each item in turn until it finds the target.
- For max or min, start from the first item, then compare the rest against it.
日本語
よくあるミス
- リニア検索は、ターゲットが見つかるまで順に各項目をチェックする。
- 最大値または最小値の場合、最初の項目から始め、残りの項目をそれと比較する。
English
Now you try
- Loop through the list to search or compare.
- Press Check answer to test your code.
日本語
あなたも試してみよう
- 検索や比較のためにリストをループで処理する。
- 回答を確認 を押してコードを試してください。
Write contains(nums, target) that returns True if target is in the list, using a linear search loop (do not use the in keyword).
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
The list nums is set. Find the largest value with a loop and store it in biggest (do not use max()).
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Find the smallest value in nums with a loop and store it in smallest (do not use min()).
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。