8. Algorithms
8.1. Filters
Search through data, select records that meet specified criteria, return a new table of selected records.
To code a filter, create an empty list, use a for loop to iterate over data, use conditional statements to check data against criteria, use the list object method append() to save selected data in the created list.
Example: the code below creates a filtered list of games that cost more than $50. Assume the price of each game is in index 1.
1games_filtered = [] # empty list to store the result23for games in games_info: # looping over the rows from the original table4 if games[1] > 50.00: # check if game cost more than 50 dollars5 games_filtered .append(movie) # add the row to games_filtered
8.2. Counters
Count the number of records/elements that meet specified criteria.
To code a counter, create and set a counter variable equal to 0, use a for loop to iterate over data, use conditional statements to check data against criteria, add +1 to counter variable if the criteria is satisfied (use augmented assignment (see section 1.5) for cleaner code).
Example: the code below counts the number of games that cost more than $50. Assume the price of each game is in index 1.
1games_count = 0 # counter, initial value set to 023for games in games_info: # looping over the rows from the original table4 if games[1] > 50.00: # check if game cost more than 50 dollars5 games_count += 1 # add 1 to count