Topic: MatApp.. a program i just made

Hello,

well, while i was studying lists subject, i found myself writing very long codes
so i started to arrange them so as to be a useful program which people can use
the program MatApp ( Matrix Application ) is a proram that deals with mathematical matrices
i.e. add matrices, multiply them
So the program is just for addition and multiplication
the rest of the code is just to make the program somehow user-friendly

def return_int(y):
    while True:
        v = raw_input("%s" % y)
        try:
            v = int(v)
        except ValueError:
            print "Should be an integer number"
        else:
            return v

def return_float(y):
    while True:
        v = raw_input("%s" % y)
        try:
            v = float(v)
        except ValueError:
            print "Should be a number"
        else:
            return v

def form_mat():
    matrix = []
    x = []
    print "Matrix RxC"
    print "Rows no^|^Columns no"
    while True:
        r = return_int("Please enter R: ")
        c = return_int("Please enter C: ")
        print "So, the matrix will be of", r, "row(s) and", c, "column(s)."
        i = 0
        j = 0
        while i < r:
            while j < c:
                element = raw_input("Please enter element(%i)(%i): "  % (i+1, j+1))
                try:
                    element = float(element)
                except ValueError:
                    print "Please enter a number."
                else:
                    x += [element]
                    j += 1
            matrix += [x]
            x = []
            i += 1
            j = 0
        return matrix

def add_row(mat):
    temp = []
    i = 0
    while i < len(mat[0]):
        element = raw_input("Please enter element(%i)(%i): " % (len(mat)+1, i+1))
        try:
            element = float(element)
        except ValueError:
            print "Not a number!"
        else:
            temp += [element]
            i += 1
    mat += [temp]
    return mat

def add_column(mat):
    temp = []
    i = 0
    x = len(mat[0])+1
    while i < len(mat):
        element = raw_input("Please enter element(%i)(%i): " % (i+1, x))
        try:
            element = float(element)
        except ValueError:
            print "Not a number!"
        else:
            mat[i].append(element)
            i += 1
    return mat

def row_times_column(m1, row, m2, column):
    temp = 0
    for i in range(len(m1[row])):
        temp += m1[row][i]*m2[i][column]
    return temp

def matrix_mult(m1, m2):
   result = []
   temp = []
   for i in range(len(m2[0])):
      for j in range(len(m1)): # The reason for taking m2[0] and m1 is that if there were 2 matrices one of 2x3 and the other of 3x2 so the resulting matrix will be of 2x2
         temp += [row_times_column(m1, i, m2, j)]
      result += [temp]
      temp = []
   return result

def scalar_mult(n, m):
    result = []
    temp = []
    for i in range(len(m)):
        for j, v in enumerate(m[i]):
            temp += [v*n]
        result += [temp]
        temp = []
    return result

def add_mat(a, b):
    # The first 3 lines are aimed to check that both matrices have the same number of rows and columns
    if len(a) == len(b):
        for i in range(len(a)):
            if len(a[i]) != len(b[i]):
                print "The matrices don't have the same number of columns.."
                break
            else: # The addition starts from here..
                result = []
                temp = []
                for i in range(len(a)):
                    for j in range(len(a[0])):
                        temp += [a[i][j] + b[i][j]]
                    result += [temp]
                    temp = []
                return result
    else:
        print "Matrices don't have the same number of rows.."

print "Please type 'help' for help"
print "type 'new' for assigning a new matrix"
mat_no = 0
mat1 = []
mat2 = []
while True:
    user_order = raw_input(">>> ")
    if (user_order.strip()).lower() == 'new':
        if mat_no == 0:
            mat1 = form_mat()
            mat_no += 1
            for i in mat1:
                print i
        elif mat_no == 1:
            mat2 = form_mat()
            mat_no += 1
            for i in mat2:
                print i
        else:
            print "You already assigned two matrices (maximum number of them)"
            ask = raw_input("If you want to replace one press 'n', else just press enter")
            if ask == 'n' or ask == 'N':
                choice = return_int('Please choose number 1 or number 2: ')
                if choice == 1:
                    mat1 = form_mat()
                elif choice == 2:
                    mat2 = form_mat()
                else:
                    print "Wrong choice"
            else:
                pass
            
    elif (user_order.strip()).lower() == 'add_mat':
        print add_mat(mat1, mat2)
    
    elif (user_order.strip()).lower() == 'add_column':
        if len(mat2) == 0:
            mat1 = add_column(mat1)
        elif len(mat1) == 0:
            print "You didn't assign any matrices yet!"
        else:
            choice = return_int('Please choose number 1 or number 2: ')
            if choice == 1:
                mat1 = add_column(mat1)
            elif choice == 2:
                mat2 = add_column(mat2)
            else:
                print "Wrong choice"
                
    elif (user_order.strip()).lower() == 'add_row':
        if len(mat2) == 0:
            mat1 = add_row(mat1)
        elif len(mat1) == 0:
            print "You didn't assign any matrices yet!"
        else:
            choice = return_int('Please choose number 1 or number 2: ')
            if choice == 1:
                mat1 = add_row(mat1)
            elif choice == 2:
                mat2 = add_row(mat2)
            else:
                print "Wrong choice"

    elif (user_order.strip()).lower() == 'scalar':
        if len(mat2) == 0:
            n = return_float('please enter the number: ')
            print scalar_mult(n, mat1)
        elif len(mat1) == 0:
            print "No matrices are available"
        else:
            choice = return_int('Please choose number 1 or number 2: ')
            if choice == 1:
                n = return_float('please enter the number: ')
                print scalar_mult(n, mat1)
            elif choice == 2:
                n = return_float('please enter the number: ')
                print scalar_mult(n, mat2)
            else:
                print "Wrong choice"
                
    elif (user_order.strip()).lower() == 'mult_mat':
        print matrix_mult(mat1, mat2)

    elif (user_order.strip()).lower() == 'mult_rc':
        row = return_int('row number: ')
        column = return_int('column number: ')
        print row_times_column(mat1, row, mat2, column)

    elif (user_order.strip()).lower() == 'exit':
        exit()

    elif (user_order.strip()).lower() == 'help':
        print """
The syntax of available functions are listed below with description..
Note that case is NOT sensitive;
for example, you can enter the command (new) like this
>>> NeW

Also, leaving whitespaces before or after the command have no effect;
for example, you can write the command (add_mat) like this
>>>         add_mat

Note: Adding or Removing a letter from the command will afect the command
i.e. your command won't work and a message appears telling you "Not available choice."

(new)
with this, you can assign a new matrix
there are only two places available for the matrices i.e. you can only assign two matrices

(add_mat)
with this, you can add two matrices
both of them should be pre-assigned
if there wasn't the second an error may occur which leads to force the program to be closed

(add_row)
with this, you can add a new row to a pre-assigned matrix

(add_column)
with this you can add a new column to a pre-assigned matrix

(scalar)
with this, you can multiply a number with a matrix

(mult_mat)
with this, you can multiply both matrices
note: be sure that you have already entered two matrices, otherwise an error may occur leading the program to be closed

(mult_rc)
with this, you can have the result of multiplication of a specific row and scpecific column
You are the one who is going to specify the row and the column

(show)
with this, you can see the matrices you assigned
if the matrix was empty, it will give you something like this:
Matrix #1:
[]

(exit)
To close the program
"""
    elif (user_order.strip()).lower() == "show":
        print "Matrix #1:"
        print mat1
        print "Matrix #2:"
        print mat2
    else:
        print "Not available choice."

I know that the code is too long and it's too hard to check the code and suggest me some tips.. so i think it would be better to use the code as a user

waiting for ur responses
feel free to comment and to ask any question  wink

Thumbs up

Re: MatApp.. a program i just made

Is this a project to help you learn Python? 

Have you considered taking input as a whole row or column at a time, perhaps comma- or space-delimited?  Even a matrix at a time.  That would be less work on a user.

If this project is not primarily for learning, consider these ideas.

You might consider some of the ideas here: http://www.math.okstate.edu/~ullrich/PyPlug/ for working with matricies. 

Look into the NumPy package.  It has n-dimensional array objects and much more.  http://numpy.scipy.org/.

Thumbs up

Re: MatApp.. a program i just made

Thanks for responding..

yeah, I wrote the code just to make myself more familiar with python

And as you suggested, I wrote another long code so as to pass the matrix to the program row by row each element is separated by a whitespace
so the code of the whole program would be:

# Ver. 1.3
def return_int(y):
    while True:
        v = raw_input("%s" % y)
        try:
            v = int(v)
        except ValueError:
            print "Should be an integer number"
        else:
            return v

def return_float(y):
    while True:
        v = raw_input("%s" % y)
        try:
            v = float(v)
        except ValueError:
            print "Should be a number"
        else:
            return v

def form_mat():
    matrix = []
    x = []
    print "Matrix RxC"
    print "Rows no^|^Columns no"
    i = 1
    while True:
        y = raw_input("Please enter raw no. (%i): " % (i))
        if (y.strip()).lower() == 'end':
            break
        if y == '':
            continue
        x = y.split()
        j = 0
        while j < len(x):
            try:
                x[j] = float(x[j])
            except ValueError:
                print "Value Error!!"
                x = []
                i -= 1
                break
            else:
                j += 1
        matrix += [x]
        x = []
        i += 1
    for z, v in enumerate(matrix):
        if len(v) == 0:
            del matrix[z]
    while True:
        l = [len(i) for i in matrix]
        a, b = max(l), min(l)
        if a != b:
            d = a - b
            print """
The number of columns aren't identical..
You have to enter %i element(s) in row %i
""" % (d, l.index(b)+1)
            while True:
                x = raw_input("Please enter: ")
                y = x.split()
                if len(y) < d:
                    print "Less than needed!!"
                    continue
                elif len(y) > d:
                    print "More than needed!!"
                    continue
                else:
                    try:
                        for i, v in enumerate(y):
                            y[i] = float(v)
                    except ValueError:
                        print "Value Error!!"
                    else:
                        matrix[l.index(b)] += y
                        break
        else:
            break
    return matrix

def add_row(mat):
    temp = []
    i = 0
    while i < len(mat[0]):
        element = raw_input("Please enter element(%i)(%i): " % (len(mat)+1, i+1))
        try:
            element = float(element)
        except ValueError:
            print "Not a number!"
        else:
            temp += [element]
            i += 1
    mat += [temp]
    return mat

def add_column(mat):
    temp = []
    i = 0
    x = len(mat[0])+1
    while i < len(mat):
        element = raw_input("Please enter element(%i)(%i): " % (i+1, x))
        try:
            element = float(element)
        except ValueError:
            print "Not a number!"
        else:
            mat[i].append(element)
            i += 1
    return mat

def row_times_column(m1, row, m2, column):
    temp = 0
    for i in range(len(m1[row])):
        temp += m1[row][i]*m2[i][column]
    return temp

def matrix_mult(m1, m2):
   result = []
   temp = []
   for i in range(len(m2[0])):
      for j in range(len(m1)): # The reason for taking m2[0] and m1 is that if there were 2 matrices one of 2x3 and the other of 3x2 so the resulting matrix will be of 2x2
         temp += [row_times_column(m1, i, m2, j)]
      result += [temp]
      temp = []
   return result

def scalar_mult(n, m):
    result = []
    temp = []
    for i in range(len(m)):
        for j, v in enumerate(m[i]):
            temp += [v*n]
        result += [temp]
        temp = []
    return result

def add_mat(a, b):
    # The first 3 lines are aimed to check that both matrices have the same number of rows and columns
    if len(a) == len(b):
        for i in range(len(a)):
            if len(a[i]) != len(b[i]):
                print "The matrices don't have the same number of columns.."
                break
            else: # The addition starts from here..
                result = []
                temp = []
                for i in range(len(a)):
                    for j in range(len(a[0])):
                        temp += [a[i][j] + b[i][j]]
                    result += [temp]
                    temp = []
                return result
    else:
        print "Matrices don't have the same number of rows.."

print "Please type 'help' for help"
print "type 'new' for assigning a new matrix"
mat_no = 0
mat1 = []
mat2 = []
while True:
    user_order = raw_input(">>> ")
    if (user_order.strip()).lower() == 'new':
        if mat_no == 0:
            mat1 = form_mat()
            mat_no += 1
            for i in mat1:
                print i
        elif mat_no == 1:
            mat2 = form_mat()
            mat_no += 1
            for i in mat2:
                print i
        else:
            print "You already assigned two matrices (maximum number of them)"
            ask = raw_input("If you want to replace one press 'n', else just press enter")
            if ask == 'n' or ask == 'N':
                choice = return_int('Please choose number 1 or number 2: ')
                if choice == 1:
                    mat1 = form_mat()
                elif choice == 2:
                    mat2 = form_mat()
                else:
                    print "Wrong choice"
            else:
                pass
            
    elif (user_order.strip()).lower() == 'add_mat':
        print add_mat(mat1, mat2)
    
    elif (user_order.strip()).lower() == 'add_column':
        if len(mat2) == 0:
            mat1 = add_column(mat1)
        elif len(mat1) == 0:
            print "You didn't assign any matrices yet!"
        else:
            choice = return_int('Please choose number 1 or number 2: ')
            if choice == 1:
                mat1 = add_column(mat1)
            elif choice == 2:
                mat2 = add_column(mat2)
            else:
                print "Wrong choice"
                
    elif (user_order.strip()).lower() == 'add_row':
        if len(mat2) == 0:
            mat1 = add_row(mat1)
        elif len(mat1) == 0:
            print "You didn't assign any matrices yet!"
        else:
            choice = return_int('Please choose number 1 or number 2: ')
            if choice == 1:
                mat1 = add_row(mat1)
            elif choice == 2:
                mat2 = add_row(mat2)
            else:
                print "Wrong choice"

    elif (user_order.strip()).lower() == 'scalar':
        if len(mat2) == 0:
            n = return_float('please enter the number: ')
            print scalar_mult(n, mat1)
        elif len(mat1) == 0:
            print "No matrices are available"
        else:
            choice = return_int('Please choose number 1 or number 2: ')
            if choice == 1:
                n = return_float('please enter the number: ')
                print scalar_mult(n, mat1)
            elif choice == 2:
                n = return_float('please enter the number: ')
                print scalar_mult(n, mat2)
            else:
                print "Wrong choice"
                
    elif (user_order.strip()).lower() == 'mult_mat':
        print matrix_mult(mat1, mat2)

    elif (user_order.strip()).lower() == 'mult_rc':
        row = return_int('row number: ')
        column = return_int('column number: ')
        print row_times_column(mat1, row, mat2, column)

    elif (user_order.strip()).lower() == 'exit':
        exit()

    elif (user_order.strip()).lower() == 'help':
        print """
The syntax of available functions are listed below with description..
Note that case is NOT sensitive;
for example, you can enter the command (new) like this
>>> NeW

Also, leaving whitespaces before or after the command have no effect;
for example, you can write the command (add_mat) like this
>>>         add_mat

Note: Adding or Removing a letter from the command will afect the command
i.e. your command won't work and a message appears telling you "Not available choice."

(new)
with this, you can assign a new matrix
there are only two places available for the matrices i.e. you can only assign two matrices
The matrix is passed to the program row by row each element is separated by just ONE space
for example:
Please enter raw no. (1): 1 2 3 4
Please enter raw no. (2): 5 6 7 8

(add_mat)
with this, you can add two matrices
both of them should be pre-assigned
if there wasn't the second an error may occur which leads to force the program to be closed

(add_row)
with this, you can add a new row to a pre-assigned matrix

(add_column)
with this you can add a new column to a pre-assigned matrix

(scalar)
with this, you can multiply a number with a matrix

(mult_mat)
with this, you can multiply both matrices
note: be sure that you have already entered two matrices, otherwise an error may occur leading the program to be closed

(mult_rc)
with this, you can have the result of multiplication of a specific row and scpecific column
You are the one who is going to specify the row and the column

(show)
with this, you can see the matrices you assigned
if the matrix was empty, it will give you something like this:
Matrix #1:
[]

(exit)
To close the program
"""
    elif (user_order.strip()).lower() == "show":
        print "Matrix #1:"
        print mat1
        print "Matrix #2:"
        print mat2
    else:
        print "Not available choice."

So.. What do you think?  neutral

Thumbs up

Re: MatApp.. a program i just made

use finally in your first function rather than else

Thumbs up

Re: MatApp.. a program i just made

use finally in your first function rather than else

Thumbs up

Re: MatApp.. a program i just made

What's "finally"? And how can I use it? - Examples, please -

Thumbs up

Re: MatApp.. a program i just made

"finally" runs code regardless of whether Python raises an exception.  It defines 'cleanup' actions that must be performed under all circumstances, regardless of whether an error occurs.  If an exception occurs in the try code, Python runs the finally block and then raises the exception again to be caught by a higher-level try-except statement.  (PYTHON: Visual Quickstart Guide.  Fehily)

try:
    # try_block
finally:
    #finally_block

"finally" and "except" cannot appear in the same "try" structure.  "else" cannot be used either.

Blessings in abundance, all the best, and ENJOY!
Art in Carlisle PA USA

Thumbs up

Re: MatApp.. a program i just made

Joker,

I would disagree with the last few posters here.  You had the code correct with the else clause in the try construct.  You do not want that else clause executed unless there is no exception and then you want it to break out of the infinite while loop.  If there is an exception, you want to prompt again.  So, I would say you had it right the first time.

I think your program looks pretty nice.  A few typographical errors to clean up if you were going to publish it.  You might consider outputting your matrices from the "show" command with one row per line so they are easier to read.

When you call split() with the specified input row, you let the separator default, i.e. you don't give any argument to split.  This means it can absorb multiple whitespace delimiters.  So: "1    2  3  4      5" does work.  See: http://docs.python.org/library/stdtypes … ng-methods .  If you did instead give an argument, such as split(' '), then multiple delimiters will return some empty strings.

Good work.

Thumbs up

Re: MatApp.. a program i just made

Oh, and here is a reference on the try construct valid syntax: http://docs.python.org/reference/compou … -statement .  You can have an else and a finally.

Thumbs up