1

I wrote a function as follows:

def change_value(array):
    for i in range(len(array)):
        for j in range(len(array[i])):
            if array[i][j]==0:
                array[i][j],array[0][0]= array[0][0],array[i][j]
            print(array[i][j],end=' ')
        print()
array=[[1,2,3],[4,0,6],[7,8,5]]
change_value(array)

This function exchanges the values ​​of the two desired indices after receiving the array. But the output was as follows:

1 2 3
4 1 6
7 8 5

What is the solution to this problem?

0

2 Answers 2

1

The problem is you're printing each value as you go - with the zero value in position (1, 1) you have already printed out the 0th row that would have had a value swapped in a future iteration.

Decouple the swapping code and the printing code:

def change_value(array):
    for i in range(len(array)):
        for j in range(len(array[i])):
            if array[i][j] == 0:
                array[i][j], array[0][0] = array[0][0], array[i][j]


def print_array(array):
    for row in array:
        for cell in row:
            print(cell, end=" ")
        print()


array = [[1, 2, 3], [4, 0, 6], [7, 8, 5]]
print_array(array)
print("===")
change_value(array)
print_array(array)
Sign up to request clarification or add additional context in comments.

Comments

0

While AKX solution is correct, note that the pythonic way to solve the problem would be

import numpy as np
array = np.array([[1, 2, 3], [4, 0, 6], [7, 8, 5]])
mask = (array == 0)

array[mask], array[0, 0] = array[0, 0], array[mask]
print(array)

3 Comments

That's a Numpy solution, not bare Python.
@AKX, agree, but there was no requirement for bare python
I wouldn't call Numpy magic (e.g. the masks and all) actually Pythonic, though -- with Numpy you need to know that (array == 0) actually returns an array, and that you can index a Numpy array with another array, etc., etc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.