Class 9 Computer Science — Searching a list
Follow a search that goes through a list from the front until it finds what it wants, and work out where it stops and how many values it had to look at.
Name: ________________________
1.This one does not stop when it finds a match. It carries on and counts them. What does the program print?
values = [4, 9, 4, 2, 4, 7] count = 0 for v in values: if v == 4: count = count + 1 print(count)2.A search that stops as soon as it finds what it wants is run on a list of 9 values, and it finds what it wants at position 6. Mark how many values it looked at.
Mark the line with an X.
3.A search that stops as soon as it finds what it wants is run on the list below. Match each value being looked for to the position the search stops at.
values = [12, 7, 19, 4, 15, 3]
- Looking for 12
- Looking for 7
- Looking for 4
- Looking for 15
- Looking for 3
- 4
- 5
- 1
- 0
- 3
4.Every value of one list is compared against every value of another here. What does the program print?
found = 0 for n in [3, 6, 9]: for m in [6, 12]: if n == m: found = found + 1 print(found)5.Two searches are run, each stopping as soon as it finds what it wants. The first is on a list of 18 values and finds what it wants at position 4. The second is on a list of 40 values and what it wants is not there at all. How many values are looked at altogether?
6.This search moves along the list until it meets the value it is looking for. What does the program print?
values = [7, 4, 6, 1, 9] i = 0 while values[i] != 6: i = i + 1 print(i)7.The same kind of search, but the last line adds one to the position before printing it. What does this program print?
values = [5, 8, 2, 9, 3, 1] i = 0 while values[i] != 9: i = i + 1 print(i + 1)8.A search that stops as soon as it finds what it wants is run four times. Put the four runs in order of how many values each one looks at, fewest first.
- Found at position 3
- Found at position 0
- Found at position 7
- Not in the list of 10 at all
Answer key — Class 9 Computer Science — Searching a list
- 1. 3
- 2. 7
- 3. Looking for 12 → 0; Looking for 7 → 1; Looking for 4 → 3; Looking for 15 → 4; Looking for 3 → 5
- 4. 1
- 5. 45
- 6. 2
- 7. 4
- 8. 1. Found at position 0 2. Found at position 3 3. Found at position 7 4. Not in the list of 10 at all