CSCI 150: PreLab 2 Answer Key
For Loops
In this optional prelab (you do not have to turn this in, it is just an additional resource), we will have an opportunity to think about nested for loops and how they can be used to create patterns (similar to our polling questions about using loops to draw shapes). There are five questions that appear in boxes below.
Nested Loop Practice
Write down the output generated by the following two chunks of code. Remember that the print method generates a new line after printing the string it is given, unless the "end" parameter asks the print to end with something else.
for i in range(1, 5) :
for j in range(1, 2*i+1) :
print("*", end="")
print("!")
Answer:**! ****! ******! ********!
for i in range(4,0,-1) :
for j in range(1, i+1) :
print(i, end="")
for j in range(1, i+1) :
print(j, end="")
print("?")
Answer:44441234? 333123? 2212? 11?
Patterns, Patterns Everywhere
In the next batch of problems, we're going to be looking for patterns in sequences of figures. For each problem, a few figures are given, each of which made out of pattern of numbers and is associated with an index (a number).
Describe the Problem: | The problem you will solve on your lab is as follows. Input: get a positive integer n indicating an index in a sequence of patterns. Output: print the n-th pattern to the console, for whichever pattern you are currently on. |
Understand the Problem: | For example, below are some indices (the numbers on the left) and their associated figures for Pattern A. Pattern A
|
Design an Algorithm: | In order to design an algorithm for this problem, we need to formulate a precise description of what the current pattern is. In particular, an algorithm to outputpattern A is as follows:
|
Below we will give you some different patterns. Your task is to (1) show that you understand each pattern, by giving the next pattern in the sequence, and (2) design an algorithm for the problem, by defining what an arbitrary line i of figure n would contain. Note that in the example above, the description of line i in figure n did not depend on i. In the following patterns, the description of a line may depend on i, n, or both.
Pattern B
1 1 1 2 2 2 3 3 3
1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
Answer:
1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 6
Answer:
Line i of figure n in Pattern B consists of the number i repeated n times. For example, line 2 of figure 5 in Pattern B consists of the number 2 repeated 5 times.
Pattern C
1 2 3 2 3 3
1 2 3 4 2 3 4 3 4 4
1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
Answer:
Line i of figure n in Pattern C consists of the numbers from i up to n. For example, line 2 of figure 5 in Pattern C consists of the numbers 2 up to 5.