Mamed
Mamed

Reputation: 772

Nested for loop for iteration

matrix = np.zeros((106, 106))

for k in result:
    p = result[0]
    for j in result:
        q = result[1]
        matrix[result.index(k), result.index(j)] = frdist(p, q)
print(matrix)

I wrote some code, now I want to iterate this code, apply for the dataset. But I am getting same result.

Why I am getting same result?

[[0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 ...
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]
 [0.13215994 0.13215994 0.13215994 ... 0.13215994 0.13215994 0.13215994]]

UPDATED:

RecursionError happens in this part. Can not be changed because it is basic part of algorithm. Any ideas?

__all__ = ['frdist']


def _c(ca, i, j, p, q):

    if ca[i, j] > -1:
        return ca[i, j]
    elif i == 0 and j == 0:
        ca[i, j] = np.linalg.norm(p[i]-q[j])
    elif i > 0 and j == 0:
        ca[i, j] = max(_c(ca, i-1, 0, p, q), np.linalg.norm(p[i]-q[j]))
    elif i == 0 and j > 0:
        ca[i, j] = max(_c(ca, 0, j-1, p, q), np.linalg.norm(p[i]-q[j]))
    elif i > 0 and j > 0:
        ca[i, j] = max(
            min(
                _c(ca, i-1, j, p, q),
                _c(ca, i-1, j-1, p, q),
                _c(ca, i, j-1, p, q)
            ),
            np.linalg.norm(p[i]-q[j])
            )
    else:
        ca[i, j] = float('inf')

    return ca[i, j]

Upvotes: 0

Views: 74

Answers (1)

ALollz
ALollz

Reputation: 59549

You want enumerate

for k, p in enumerate(result):
    for j, q in enumerate(result):
        matrix[k, j] = frdist(p, q)

Upvotes: 1

Related Questions