For this programming challenge we will investigate different functions which will all be based on a linear search algorithm.
Let’s consider a teacher who has decided to keep track of rewards issued to their students throughout the term by adding their name at the end of a text file each time they win a reward for their positive attitude and effort in lessons.
The teacher would like to write a few Python functions to:
- scan the content of the text file and check if a particular students has received a reward or not,
- count the number rewards a student has received throughout the term.
- locate a student in the text file (identify the position/line number where the student’s name appear in the text file)
The teacher has started the code by creating a function called readTextFile() that takes a parameter called filename/ This function scan the context of the text file and return a list of all the names listed in the text file.
Using flowcharts, the teacher then worked out the algorithms for the extra functions they would like you to implement and test to complete the code. You can access these flowcharts below.
Python Code
You can now complete and test all three functions using the flowcharts provided above. The trinket below contains two tabs. In the second tab called “rewards.txt” you can access the content of the text file.
Alternative Approach
The Python syntax allows you to use loop through a list of values as follows:
for value in list: print(value)
Not all programming languages will let you use this syntax. An alternative approach is to use indices:
for i in range(0,len(list)): print(list[i])
In this case the flowchart for our count() function would become:
Solution...
The solution for this challenge is available to full members!Find out how to become a member:
➤ Members' Area