Hello!
I'm studying Python and wrote a very simple class to work with bidimensional arrays - just as an exercise.
Before writing te class I played around with functions and they worked fine.
When I tried to do the same using a class, things became strange...
Okay, I wrote this class:

import random

class Matriz:
	
	matriz = []

	def __init__ (self, grau_matriz, inicio):
	
		self.__grau_matriz = grau_matriz
		
		if inicio == 0:
			self.zero()
		elif inicio == 1:
			self.aleatoria()

	def zero(self):

		for i in range(self.__grau_matriz):
			linha = []
			for j in range(self.__grau_matriz):
				linha.append(0)
                
		self.matriz.append(linha)
			
	def aleatoria(self):
		for i in range(self.__grau_matriz):
			linha = []
			for j in range(self.__grau_matriz):
				linha.append(random.randrange( 1, 10 ))
				
                
		self.matriz.append(linha)

	def mostra(self):
		for i in range(self.__grau_matriz):
			for j in range(self.__grau_matriz):
				print "%2d " % self.matriz[i][j],
			print

		print

To teste this class, I wrote this;

# Use Matriz class

from Matriz import Matriz

matriz1 = Matriz(3,0) 

matriz1.mostra()
print

And the result is "IndexError: list index out of range" in mostra method, when it tries to run this line: print "%2d " % self.matriz[j],

I ask, why??

So far I did not find where I did it wrong.

Thanks very much for any hints! :)

Hello!
Well... aham... I found the bug.

The line in which I appended the values to the array was outside the for. Hence the index out of range error message.

The for structure should read, then:

def zero(self):
		for i in range(self.grau_matriz):
			linha = []
			for j in range(self.grau_matriz):
				linha.append(0)
                
			self.matriz.append(linha)

This is valid for both methods in which I use the same idea...

Thanks! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.