0
def ones_in_corners(n):
    '''
    Creates an nxn matrix full of 0s, except the corners of the matrix
    will have 1s in it.
    eg. ones_in_corners(3) would give us
    1 0 1
    0 0 0
    1 0 1
    :param n: the size of the square matrix
    :return:
    '''
    # setup a single row of n ' ' (space) chars
    row = ['0'] * n
    # now we will make the mat have n rows
    mat = [row] * n
    # the following four lines make it so only
    # the corners of the matrix has 1s
    mat[0][0] = '1'
    mat[0][n-1] ='1'
    mat[n-1][0] = '1'
    mat[n-1][n-1] = '1'
    return mat

print(ones_in_corners(3)) ''' output is [['1', '0', '1'], ['1', '0', '1'], ['1', '0', '1']] but I want it to be [['1', '0', '1'], ['0', '0', '0'], ['1', '0', '1']] '''

Jim Lahey
  • 11
  • 1
  • What seems to be the problem? – DYZ Nov 15 '20 at 00:28
  • Please provide the expected [MRE](https://stackoverflow.com/help/minimal-reproducible-example). Show where the intermediate results deviate from the ones you expect. We should be able to paste a single block of your code into file, run it, and reproduce your problem. This also lets us test any suggestions in your context. This code defines a function and quits without executing. – Prune Nov 15 '20 at 00:28
  • When the function is called print(ones_in_corners(3)) the output is [['1', '0', '1'], ['1', '0', '1'], ['1', '0', '1']] but I need it to be [['1', '0', '1'], ['0', '0', '0'], ['1', '0', '1']] – Jim Lahey Nov 15 '20 at 00:34
  • The quick answer would be, when defining matrix use `matrix = [['0'] * n for _ in range(n)` The problem lies in `row = ['0'] * n; mat = [row] * n`, here you are basically referencing original `row` n times (not creating new ones) – ssp4all Nov 15 '20 at 01:00

0 Answers0