0

I'm just starting python and it seemed reasonable to go ahead and learn the new version. I read that numpy wont be available for python3 until at least 2010. All I need is a basic "vector", "matrix", and some basic functions like matrix/vector multiplication. Is anything like this available for python3?

Thanks,
Dave

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by sneekula
0

I guess you can play around with lists and lists of lists.

For example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

mx = make_matrix(3, 3)

print(mx)

print('-'*34)

# now populate the zero matrix
# for instance put a 5 in row 0, column 0
mx[0][0] = 5
# put a 7 in row 1, column 1
mx[1][1] = 7
# put a 9 in row 2, column 2
mx[2][2] = 9

print(mx)

"""
my result -->
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
----------------------------------
[[5, 0, 0], [0, 7, 0], [0, 0, 9]]
"""

Another example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

rows = 5
cols = 5
mx = make_matrix(rows, cols)

# pretty show the matrix
for x in mx:
    print(x)

print('-'*16)

# load matrix with a diagonal of ones
for row in range(rows):
    for col in range(cols):
        if col == row:
            mx[row][col] = 1

# pretty show the matrix
for x in mx:
    print(x)

"""
my result -->
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
----------------
[1, 0, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 0, 1, 0]
[0, 0, 0, 0, 1]
"""
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.