I want to create this:
1 0 0 0 0 0
1 1 0 0 0 0
1 1 1 0 0 0
1 1 1 1 0 0
1 1 1 1 1 0
1 1 1 1 1 1
However, I prefer if a library is used to create this, how do I go about doing this?
Note: NumPy can be used to create the array as well.
There are a lot of answers on SO, but they all provide answers that do not use libraries, and I haven't been able to find anything online to produce this!
CodePudding user response:
You can use np.tril
:
>>> np.tril(np.ones((6, 6), dtype=int))
array([[1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1]])
CodePudding user response:
Using numpy.tri
Syntax:
numpy.tri(N, M=None, k=0, dtype=<class 'float'>, *, like=None)
Basically it creates an array with 1
's at and below the given diagonal and 0
's elsewhere.
Example:
import numpy as np
np.tri(6, dtype=int)
>>>
array([[1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1]])