Good job! In this lesson, we covered:
- Iterables and iterators and how they differ.
- Using the
iter()funtion to create an iterator.
- Using the
next()function to manually iterate over an iterator.
forloops use iterables and iterators.
- How to write custom iterators by implementing the
- How to use built-in
Let’s practice these concepts some more!
Create a list iterable that contains tuples of
(cat_toy, price). The list should be called
cat_toys. The tuple should consist of the cat toy name and price following the values in the table:
iter(), create an iterator called
cat_toy_iterator that retrieves the iterator for
next() statements, print out each value in
A customer enters and only has $15 to spend on exactly 2 cat toys. They want to know how many combinations of the available toys they can afford, while only getting 2 of them total.
itertools at the top of the module.
Next, above the commented out
for loop, create a
combinations() iterator called
toy_combos to retrieve all combinations of 2 total toys from the
Uncomment all lines of the
Each iteration of the
for loop gives a tuple that is within
toy_combos. The variable
toy1 represents index
0 of the tuple (the toy name) and
cost_of_toy1 represents index
1 of the tuple (the toy cost). We repeat this to store the toy name and price of toy 2 via variables
After the final line within the
for loop, check if the price of
cost_of_toy2 is less than or equal to
max_money which is the max $15 the customer has to spend. If it is, add the tuple to the
Print the final
options list to see what toy combinations the customer can buy with $15.