python matrix condensed to square

Solutions on MaxInterview for python matrix condensed to square by the best coders in the world

showing results for - "python matrix condensed to square"
Addie
20 Sep 2016
1>>> square_to_condensed(1, 2, len(points))
23
3>>> dist_condensed[3]
44.4721359549995796
5>>> dist[1,2]
64.4721359549995796
Soan
10 Jan 2019
1import math
2
3def calc_row_idx(k, n):
4    return int(math.ceil((1/2.) * (- (-8*k + 4 *n**2 -4*n - 7)**0.5 + 2*n -1) - 1))
5
6def elem_in_i_rows(i, n):
7    return i * (n - 1 - i) + (i*(i + 1))//2
8
9def calc_col_idx(k, i, n):
10    return int(n - elem_in_i_rows(i + 1, n) + k)
11
12def condensed_to_square(k, n):
13    i = calc_row_idx(k, n)
14    j = calc_col_idx(k, i, n)
15    return i, j
Mía
01 Feb 2020
1def square_to_condensed(i, j, n):
2    assert i != j, "no diagonal elements in condensed matrix"
3    if i < j:
4        i, j = j, i
5    return n*j - j*(j+1)//2 + i - 1 - j