Advertisement
UsSe3wa

Untitled

Apr 16th, 2025
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. # MatveyPanchenko DSAI-03
  2. from copy import deepcopy
  3.  
  4. tr = lambda m: [list(r) for r in zip(*m)]
  5.  
  6. def rref(a, eps=1e-12):
  7.     A = deepcopy(a)
  8.     r = c = 0
  9.     rows, cols = len(A), len(A[0])
  10.     piv = []
  11.     while r < rows and c < cols:
  12.         k = next((i for i in range(r, rows) if abs(A[i][c]) > eps), None)
  13.         if k is None:
  14.             c += 1
  15.             continue
  16.         A[r], A[k] = A[k], A[r]
  17.         p = A[r][c]
  18.         A[r] = [x / p for x in A[r]]
  19.         for i in range(rows):
  20.             if i != r and abs(A[i][c]) > eps:
  21.                 f = A[i][c]
  22.                 A[i] = [u - f * v for u, v in zip(A[i], A[r])]
  23.         piv.append(c)
  24.         r += 1
  25.         c += 1
  26.     return A, piv
  27.  
  28. row_basis = lambda a: [r for r in rref(a)[0] if any(abs(x) > 1e-12 for x in r)]
  29. def col_basis(a):
  30.     _, piv = rref(a)
  31.     return [[a[i][j] for i in range(len(a))] for j in piv]
  32.  
  33. def null_basis(a):
  34.     R, piv = rref(a)
  35.     n = len(R[0])
  36.     free = [j for j in range(n) if j not in piv]
  37.     B = []
  38.     for f in free:
  39.         v = [0] * n
  40.         v[f] = 1
  41.         for i, p in enumerate(piv):
  42.             v[p] = -R[i][f]
  43.         B.append(v)
  44.     return B
  45.  
  46. if __name__ == "__main__":
  47.     r = int(input("rows: "))
  48.     A = [list(map(float, input().split())) for _ in range(r)]
  49.     print("Row space:", row_basis(A))
  50.     print("Column space:", col_basis(A))
  51.     print("Row null space:", null_basis(tr(A)))
  52.     print("Column null space:", null_basis(A))
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement