I have to print this python code in a 5x5 array the array should look like this :
0 1 4 (infinity) 3 1 0 2 (infinity) 4 4 2 0 1 5 (inf)(inf) 1 0 3 3 4 5 3 0
can anyone help me print this table? using indices.
for k in range(n): for i in range(n): for j in range(n): if A[i][k]+A[k][j]<A[i][j]: A[i][j]=A[i][k]+A[k][j]
Example. public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].
In Python, we can access two-dimensional array elements using two indices. The first index refers to the list's indexing and the second one refers to the elements' position. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.
ALGORITHM: STEP 1: Declare and initialize an array. STEP 2: Loop through the array by incrementing the value of i. STEP 3: Finally, print out each element of the array.
A combination of list comprehensions and str
joins can do the job:
inf = float('inf') A = [[0,1,4,inf,3], [1,0,2,inf,4], [4,2,0,1,5], [inf,inf,1,0,3], [3,4,5,3,0]] print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in A]))
yields
0 1 4 inf 3 1 0 2 inf 4 4 2 0 1 5 inf inf 1 0 3 3 4 5 3 0
Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:
for i in range(n): for j in range(n): print '{:4}'.format(A[i][j]), print
The more Pythonic cousin would be:
for row in A: for val in row: print '{:4}'.format(val), print
However, this uses 30 print statements, whereas my original answer uses just one.
There is always the easy way.
import numpy as np print(np.matrix(A))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With