Python and matrix of objects - python

I'm new to Python. I use version 3.3. I'm doing something wrong but I can't find.
I create tb1, an array of objects.
Content is initialized and then printed.
I create tb2, a second array.
The content of tb1 is then copied into tb2 while transposing rows and columns.
A second print shows that tb1 is altered. I can't understand why.
The problem do not happen with a matrix of integers.
Results of prints are:
123456789
123256369
#!/bin/python3
class Item:
n=0
m=0
class Tb:
items = [[Item() for i in range(3)] for j in range(3)]
tb1 = Tb()
for i in range(3):
for j in range(3):
tb1.items[i][j].n = i*3+j+1
# print original content of tb1
for i in range(3):
for j in range(3):
print( tb1.items[i][j].n, end="")
print()
tb2 = Tb()
for i in range(3):
for j in range(3):
tb2.items[j][i].n = tb1.items[i][j].n
# print content of tb1. It is altered
for i in range(3):
for j in range(3):
print( tb1.items[i][j].n, end="")
print()

class Tb:
items = [[Item() for i in range(3)] for j in range(3)]
Here you are creating a class variable items that will be shared by all instances of Tb. To create instance variables, use __init__:
class Tb:
def __init__(self):
self.items = [[Item() for i in range(3)] for j in range(3)]

Related

How to make a matrix that only holds None values?

I have to write a function empty_matrix that must return a list of lists (a matrix)
desired output:
empty_matrix(3,4)
returns a list with three lists each of length four:
[[None,None,None,None],[None,None,None,None],[None,None,None,None]]
What should I change in my code below???
def empty_matrix(row,column):
first_col = []
for x in range(len(matrix)):
sublist = matrix[x]
for y in range(len(sublist)):
first_col.append(matrix[x][y])
Using a list comprehension:
def empty_matrix(row, column):
return [[None for _ in range(row)] for _ in range(column)]
But to fix your code, you're using len on variables matrix and sublist that aren't defined, your indentation is off, try something like this if you don't want to use a list comprehension.
def empty_matrix(row, column):
matrix = []
for c in range(column):
column = []
for r in range(row):
column.append(None)
matrix.append(column)
return matrix

Python generate combinations of N in class K

I have this code
def array_combos(n,k):
arCombos = []
i = 0
a = [0]*k
while i > -1:
for j in range(i+1, k):
a[j] = a[j-1]+1
i=j
print(a)
arCombos.append(a)
while a[i] == i + n - k:
i -= 1
a[i] += 1
return arCombos
The print(a) print right values but list that function return is popolate by one single array n times.
If I use yield insted of popolate list function work perfectly.
Can we help?
Tks
The arCombos.append(a) always append the same, and only, instance of a, so you save it to the main arCombos multiple times, but there is still one instance that keep being modified.
Pass a copy of it with code like, more at Get a copy of list
arCombos.append(a[:])
arCombos.append(list(a))

Error: 'Matrix' object is not subscriptable

I have created a class in python for matrices and want to have different functions that when applied to a matrix object accomplishes a specific goal. The specific function which have an error is a function to add one matrix to another.
class Matrix:
def __init__(self, rows):
self.rows = rows
self.m = len(rows)
self.n = len(rows[0])
def add(self,other):
output = [[0 for x in range(self.m)] for y in range(self.m)]
for i in range(self.m):
for j in range(self.n):
output[i][j] = self[i][j] + other[i][j]
returnmatrix = Matrix(output)
return returnmatrix
B = Matrix([[1,2,3], [4,5,6], [7,8,9]])
F = Matrix([[1,2,3], [4,5,6], [7,8,9]])
B.add(F)
I expect the output to be a 3x3 matrix that is the addition of matrices B and F. Error recieved is: TypeError: 'Matrix' object is not subscriptable.
The error comes from this line;
for j in range(self.n):
output[i][j] = self[i][j] + other[i][j]
You are subscripting the object but presumably need to be subscripting the rows attribute:
for j in range(self.n):
output.rows[i][j] = self.rows[i][j] + other.rows[i][j]
Also for this to work you need to create output as an instance of Matrix before this, so the full function would be:
def add(self,other):
output = Matrix([[0 for x in range(self.m)] for y in range(self.m)])
for i in range(self.m):
for j in range(self.n):
output.rows[i][j] = self.rows[i][j] + other.rows[i][j]
return output
Also as an aside if you are creating methods like add you should look into dunder methods (e.g. __add__); which will give you the nice functionality of being able to use the plus symbol to add instances of your object together.

Python List/Tuple

Hi i want to modify my list so it shows an (x) at the given coordinate via tuple.
Here is my code so far
#w=width
#h=height
#c=coordinates
new_grid = []
def coordinates(w,h,c):
'''
>>> coordinates(2, 4, (0, 1))
>>> print(new_grid)
[['(_)', '(x)'], ['(_)','(_)'], ['(_)', '(_)'], ['(_)', '(_)']]
'''
b=[]
for i in range(h):
new_grid.append(b)
for j in range(w):
c=('(_)')
b.append(c)
i am not sure how to implement (x) at the given coordinates, any help is appreciated
thanks.
There are multiple errors in your approach:
You declare the global variable new_grid, but later you have grid.append(b)
Globals are usually not needed, you could create the grid in the function and update the global using the function's return value
The two for-loops are separate. Remember that indentation matters in Python
b is declared outside of the loops, and so you append to the same instance all the time
You overwrite your original coordinate tuple c with the string '(_)'
Here's a version that I think does what you were originally after:
def coordiantes(w,h,c):
'''
>>> print(coordiantes(2, 4, (0, 1)))
[['(_)', '(x)'], ['(_)','(_)'], ['(_)', '(_)'], ['(_)', '(_)']]
'''
grid = []
for i in range(h):
b = []
grid.append(b)
for j in range(w):
if (i, j) == c:
b.append('(x)')
else:
b.append('(_)')
return grid
You could also implement the whole thing as a list comprehension:
def coordiantes(w, h, c):
return [['(x)' if c == (y, x) else '(_)' for x in range(w)]
for y in range(h)]

editing a list of lists python3

I have the following code
class Board:
def __init__(self, size=7):
self._size = size
self._list, self._llist =[],[]
for i in range (self._size):
self._list.append('_ ')
for j in range(self._size):
self._llist.append(self._list)
def printboard(self):
for i in range(self._size):
for j in range(self._size):
print(self._llist[i][j], end = ' ')
print('\n')
def updateboard(self,x,y,letter):
self._llist[x][y]=letter
self.printboard()
board = Board(3)
board.updateboard(0,0,'c')
and this prints
c _ _
c _ _
c _ _
instead of
c _ _
_ _ _
_ _ _
I can't see what is going wrong. Also, is there a simpler way to create the list of lists dynamically?
Thanks!
You are creating llist with the same list object, repeated multiple times. If you want each list in llist to be a separate, independent object (so that when you modify the contents only one list is changed) then you need to append a different copy to each. The easiest way to do this is to change:
self._llist.append(self._list)
to
self._llist.append(list(self._list))
Simpler code would be:
self._list = ['_ '] * self._size
self._llist = [list(self._list) for i in range(self._size)]

Categories

Resources