Week 7 Refresher¶
This week you will only have one problem to solve for the refresher. Use the cookbook to help you solve it. I have given you little code here so that you can connect the way I describe code to the code itself better.
Nested for loops¶
Sometimes in Computer Science, having loops that are inside other loops are really useful. When this happens, we can refer to the loops as layers. Think of it like an onion.
Requirements:
- Write two
forloops, one inside the other. - The outer
forloop should start at 1 and go to 20. - The inner
forloop should start at 1 and go to 10.
- The outer
- Write two
Before both
forloops, create an emptylist.- Inside the inner
forloop, multiply the two loop variables. - if you aren’t sure what I mean by “loop variable”, check the cookbook.
- Inside the inner
- Check if the resulting number is inside the list yet.
- If you aren’t sure what I mean by “is inside”, check the
listpart of the cookbook
- If you aren’t sure what I mean by “is inside”, check the
If the result is not in the
list, then add it to thelist.After both loops are finished, print out the length of the
list.
Things to observe:
- What happens if you change the sizes of the loops? For instance, if you make the 20 number into 200? Do you notice anything about the speed of the code?
- I have written about
set`s in the cookbook. Use a :code:`setinstead of alist. Is it faster? - Count how much faster it is. Do this using the
timemodule. This is also in the cookbook.