0
\$\begingroup\$

A robot can move in one step from cell X to cell Y if and only if the distance between the centers of the cells X and Y measured in meters is equal to the sum of integers contained in X and Y. It then returns the index of the cell which the above condition does not meet which is the index only [0, 1, 4] and its value is [3, 1, 0].

How can I improve my code and reduce the time complexity?

def row_walk(matrix):

    result = []
    x = []
    y = []
    for i, r1 in enumerate(matrix):
        y.append(i)
        for j, r2 in enumerate(matrix):
            if r1+r2 == abs(i-j) and not j <= i:
                x.append((i, j))
    result.append((list({el for tup in x for el in tup})))

    z = []
    for t1 in y:
        if t1 not in result[0]:
            z.append(t1)
    return z

if __name__=="__main__":
    matrix = [3, 1, 3, 2, 0, 0]
    print(row_walk(matrix))
\$\endgroup\$
3
\$\begingroup\$

First, you are defining too many variables. Instead of making a list of tuples and then converting it to a flattened list with a different name, you should make the list out of numbers in the first place. It would also be better to use a set instead of a list. Your if statement is a little odd. not j <= i is the same as j > i, but harder to read. If j must be greater than i, why does your first check include abs()? Since j > i is an easier operation than the other check, it should come first. That way, if it is False, the other check won't even be evaluated and the whole thing is more efficient. You could also use a comprehension instead of a four-line for loop:

def row_walk(matrix):
    used = set()
    for i, r1 in enumerate(matrix):
        for j, r2 in enumerate(matrix):
            if j > i and r1+r2 == j-i:
                used.update((i, j))
    return [x for x in range(len(matrix)) if x not in used]

If you can use a set instead of a list, you can use a better return statement:

return used.symmetric_difference(range(len(matrix))

This all assumes that you are using Python 3. If you are using Python 2, use xrange() instead of range(). Although range() still exists in Python 2, it creates a list instead of an iterator.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.