Python: Generating A Symmetric Array With List Comprehension
I am trying to generate a matrix A == [f(i,j) for i,j in range(0,n)]. The matrix is symmetric (f(i,j) == f(j,i)) and the diagonal elements are zero (f(i,i) == 0). Question: Is it p
Solution 1:
Assuming you really need the full matrix, in spite of its being symmetric, you could do this.
Create the matrix A first. (I know, this means you're not generating it in a list comprehension.) Here I define a 'dummy' function f and assume a value of 3 for n.
>>>n=3>>>subs=((i,j) for i inrange(n) for j inrange(3) if i<=j)>>>for i,j in subs:... i,j...
(0, 0)
(0, 1)
(0, 2)
(1, 1)
(1, 2)
(2, 2)
>>>deff(i,j):...return...>>>defg(i,j):...if i==j:... A[i,i] = 0...else:... val=f(i,j)... A[i,j]=val... A[j,i]=val
If I've understood you correctly, there's no need for extra storage. Call g in a list comprehension that exercises subs.
Solution 2:
If you want the function to execute only when i < j, you can use lru_cache (@lru_cache) to save the results of the function in cache, and use it directly without re-calculating it when i > j.
from typing import Any
from functools import lru_cache
@lru_cache()
def f(i: int, j: int) -> Any:
return i * (-j)
n = 5
m = [f(i, j) if i < j else f(j, i) if i > j else0for i in range(n)for j in range(n)]
for i in range(0, n * n, n):
print(m[i: i + n])
Results in
[0, 0, 0, 0, 0]
[0, 0, -2, -3, -4]
[0, -2, 0, -6, -8]
[0, -3, -6, 0, -12]
[0, -4, -8, -12, 0]
Post a Comment for "Python: Generating A Symmetric Array With List Comprehension"