11 Prove : Homework - Data Structures
List Comprehensions
Outcomes
At the end of this study, successful students will be able to:
Show fluency in discussing list comprehensions.
Use list comprehensions in Python to solve problems.
Overview
A Python feature that is commonly used to filter, generate, and manipulate lists is that of List Comprehensions.
Preparation Material
Please read the following:
DataCamp: Python List Comprehensions - Please skip the section entitled "Lambda Functions with map(), filter() and reduce()", we will read about them next week...
(Optional) Python List Comprehensions: Explained Visually - You can refer to this for further explanation, if you would like.
Programming Assignment
Practice using list comprehensions.
Instructions
Write a program that uses a list comprehensions to generate lists for each of the following:
A list of the first 100 squares of the numbers [0-99] (e.g., 0, 1, 4, 9, 16, 25, ...)
A list of the numbers between 0 and 99, inclusive, that are divisible by 5 or 7 (e.g., 5, 7, 10, 14, 20, 21, ...).
Take a provided list of words and return a list containing only those that have at least 4 letters and that contain the letter 'e'.
To accomplish this, begin with the following code:
"""
Purpose: This file is a starting point to help you practice list comprehensions.
"""
def get_part1_list():
"""
Returns a list of the squares of the numbers [0-99], e.g., 0, 1, 4, 9, 16, 25 ...]
"""
numbers = [] # TODO: Change this line to be a list comprehension
return numbers
def get_part2_list():
"""
Returns a list of the the numbers [0-99] that are divisible by either 5 or 7
"""
numbers = [] # TODO: Change this line to be a list comprehension
return numbers
def get_part3_list():
"""
Filters a list of words to return only those that are at least 4 letters long and contain an 'e'
"""
old_words = ["tacos", "knowledge", "water", "on", "the", "I", "is", "hilarious", "tie", "coat", "white", "covenants", "phone", "rubric", "send", "restrictions"]
new_words = [] # TODO: Change this line to be a list comprehension
return new_words
def main():
"""
This function calls the above functions and displays their result.
"""
print(get_part1_list())
print(get_part2_list())
print(get_part3_list())
if __name__ == "__main__":
main()
Your task is to insert list comprehensions into the 3 places noted. Then, verify that your program displays the correct results.
Testing your program
An automated testBed script is not available for your program. Instead, please manually test your program and ensure that it works correctly.
Submission
You are encouraged to work with others on the programming and the quiz.
When you have a good understanding of this data structure and have completed the programming project, take the accompanying I-Learn Quiz. It has questions about how the data structure works, and also, has places for your to report on the parts of the programming assignment that you completed.