Reputation: 97
How do you use nested for loops to print out the following pattern? So you don't have to write 10 for loops for it.
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 54 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Upvotes: 2
Views: 266
Reputation: 1241
Simply increase your step size!
for stepSize in range(10):
for count in range(10):
print((count + 1) * (stepSize + 1), end=" ")
# count loop has ended, back into the scope of stepSize loop
# We are also printing(" ") to end the line
print(" ")
# stepSize loop has finished, code is done
Explanation:
The first, outer loop is increasing our step size, then for each step size we count up 10 steps and finish the line when we print(" ")
in the outer for loop.
Upvotes: 2
Reputation: 4745
This is going to be one of the least interpretable answers, but I had fun trying to write a one-liner:
num_rows = 10
print '\n\n'.join(' '.join(str(i) for i in range(j,(num_rows+1)*j)[::j]) for j in range(1,num_rows+1))
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Disecting it, range(j,(num_rows+1)*j)[::j]
generates the integers for each line where j
is ranging over the row number (starting with an index of 1 as you ask for). The [::j]
part gives you every j
-th element of the list. Then the inner join statement is constructing the line string from the list of integers, each integer separated by a space ' '
. The outer join constructs the final output by combining the lines of integers with \n\n
, which is a double new line to put a blank line in between each line of integers.
I think the other solutions are more readable, but this one is kind of fun.
Upvotes: 0
Reputation: 39
This is how I would do it:
for x in range (1,11):
product = []
for y in range (1, 11):
current_product = x * y
product.append(current_product)
print(*product, sep=' ')
Upvotes: 0