Grade 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.A search that stops as soon as it finds what it wants is run on a list. Sort each of these by how many values the search looks at.
Groups: Looks at 3 values · Looks at 6 values
- The value is five steps along from the front
- The value is at position 2
- The value is the third one in the list
- The value is two steps along from the front
- The value is at position 5
- The value is the sixth one in the list
2.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)3.Why does a search have to look at every value in a list before it can say that the value it wants is not there?
- a) Because the value it has not looked at yet could be the one
- b) Because a search cannot count how many values it has looked at
- c) Because a list has no way of saying how long it is
- d) Because the search always begins at the last value
4.A search that stops as soon as it finds what it wants is run on a list of 30 values, and the value it is looking for is not in the list at all. How many values does it look at before it can say so?
- a) 15
- b) 29
- c) 30
- d) 1
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.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)7.This search does not stop early. It goes through the whole list and remembers where the match was. What does it print?
values = [8, 3, 9, 5, 2] at = 0 for i in range(0, len(values)): if values[i] == 9: at = i print(at)8.The value being looked for appears twice in this list. What does the program print?
values = [5, 8, 5, 8] i = 0 while values[i] != 8: i = i + 1 print(i)
Answer key — Grade 9 Computer Science — Searching a list
- 1. The value is at position 2 → Looks at 3 values; The value is at position 5 → Looks at 6 values; The value is the third one in the list → Looks at 3 values; The value is the sixth one in the list → Looks at 6 values; The value is two steps along from the front → Looks at 3 values; The value is five steps along from the front → Looks at 6 values
- 2. 3
- 3. a) Because the value it has not looked at yet could be the one
- 4. c) 30
- 5. 45
- 6. 1
- 7. 2
- 8. 1