Good job! In this lesson, we covered:
- What an iterable is
- What an iterator is
- How to use built-in functions
- How for loops use iterators
- How to write custom iterators
- How to use built-in itertools
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 he only has $15 to spend on exactly 2 cat toys. He wants to know how many combinations of the available toys he 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 man has to spend. If it is, add the tuple to the
Print the final
options list to see what toy combinations the man can buy with $15.