Question

I can find matrix dimensions if we see m_1 matrix but if I have something like m_2 matrix I can't check it. Where am I wrong?

  def matrixDimensions(m):
    test = []
    y = len(m)
    for x in m:
        len(x)
        test.append(len(x))
        if test[1:] != test[:-1]:
            return "This is not a valid matrix."
        else:
            return 'This is a %dx%u matrix.' % (y,len(x))

    m_1 = [ [1, 3, 2], [-5, 6, 0] ]
    matrixDimensions(m_1)

    m_2 = [ [1, 3], [-5, 6, 0] ]
    matrixDimensions(m_2)
Was it helpful?

Solution

def matrixDimensions(m):
    test = len(m[0])
    y = len(m)
    for x in m:
        if test!=len(x):
            print "This is not a valid matrix."
            return
    print 'This is a %dx%u matrix.' % (y,len(m[0]))

m_1 = [ [1, 3, 2], [-5, 6, 0] ]
matrixDimensions(m_1)

m_2 = [ [1, 3], [-5, 6, 0] ]
matrixDimensions(m_2)

OTHER TIPS

The main thing here is that m_2 is not a valid matrix.

You're also doing some unusual things in your code, such as comparing test[1:] with test[:-1]. This is not comparing two values, but two lists. I don't think this is what you mean to do.

I'm also not sure why you are returning strings, but that's a problem for another day.

def matrixDimensions(m):
    for i in range(1,len(m)):
       if len(m[i]!=len(m[i-1]): return "This is not a valid matrix"
    return "This is a %u x %u matrix" % (len(m),len(m[0]))

m_1 = [ [1, 3, 2], [-5, 6, 0] ]
matrixDimensions(m_1)

m_2 = [ [1, 3], [-5, 6, 0] ]
matrixDimensions(m_2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top