Posts: 382
Threads: 94
Joined: Mar 2017
Hi all ! With C++ no problem, I can begin a for loop by 1. I should like to delete all multipilcations by 0, as we find multiplication tables in a school.
print("MULTIPLICATION TABLE")
M=[[0,1,2,3,4,5,6,7,8,9],
[1,1,1,1,1,1,1,1,1,1],
[2,2,2,2,2,2,2,2,2,2],
[3,3,3,3,3,3,3,3,3,3],
[4,4,4,4,4,4,4,4,4,4],
[5,5,5,5,5,5,5,5,5,5],
[6,6,6,6,6,6,6,6,6,6],
[7,7,7,7,7,7,7,7,7,7],
[8,8,8,8,8,8,8,8,8,8],
[9,9,9,9,9,9,9,9,9,9]]
for i in range (len(M)):
for j in range (len(M)):
M[i][j] =i*j
for x in range (len(M)):
print(M[x])
Posts: 331
Threads: 2
Joined: Feb 2017
range accepts additional argument for starting value of sequence; you can use
for i in range(1, 4):
print(i) to get
Output: 1
2
3
Posts: 382
Threads: 94
Joined: Mar 2017
Thanks . With "for x in range (1,10)" in the print statement, I only suppressed the fist line. How to soppress leading zeros of all following lines ?
Here is my output:
/usr/bin/python3.5 /home/sylvain/PycharmProjects/Py4/lambda.py
MULTIPLICATION TABLE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54]
[0, 7, 14, 21, 28, 35, 42, 49, 56, 63]
[0, 8, 16, 24, 32, 40, 48, 56, 64, 72]
[0, 9, 18, 27, 36, 45, 54, 63, 72, 81]
Posts: 331
Threads: 2
Joined: Feb 2017
print M[x][1:] instead of M[x]. Actually you dont need to use range to remove first elements, you can use
for row in M[1:]:
print(row[1:])
Posts: 382
Threads: 94
Joined: Mar 2017
Thanks again. Now I have a good multiplication table. Last question: is it possible to avoid the matrix I have on the top of the file ?
Posts: 8,160
Threads: 160
Joined: Sep 2016
Of course, you can use list comprehension
multiplication_table = [[x*y for y in range(1,10)] for x in range(1,10)]
print(multiplication_table) in any case, no need to create the table in advance and then change each element
multiplication_table = []
for x in range(1,10):
new_row = []
for y in range(1,10):
new_row.append(x*y)
multiplication_table.append(new_row)
print(multiplication_table)
Posts: 382
Threads: 94
Joined: Mar 2017
Thanks to Buran. Indeed python language is very strong, and therefor hard to leatn.
Posts: 2,953
Threads: 48
Joined: Sep 2016
These are the range arguments: range(start, stop, step).
In [1]: for num in range(2, 21, 2):
...: print(num, end=" ")
...:
2 4 6 8 10 12 14 16 18 20
|