Python: Assignment or erroneous data printing in nodes

0

I recently started a question about python, the problem was solved, but now all I need is to solve a problem with assigning and printing values of one (or several) instances of a class.

I enclose the output on the screen:

I attach the code:

class Nodo():
    def __init__(self,f):
        self.siguiente = ''
        self.pos = f
        self.elemento = ''
        self.info = NodoInfo(self.pos)

    def getSiguiente(self):
        return self.siguiente

    def setSiguiente(self,n):
        self.siguiente = n

    def getPos(self):
        return self.pos

    def setElemento(self,a):
         self.elemento = a

    def getElemento(self):
        return self.elemento

    def getInfo(self):
        return(self.info.getTitulo())

class NodoInfo():
    def __init__(self,pos):
        self.titulo = "Numero de nodo: "+str(pos)
        self.desc = "Este nodo puede almacenar datos."
        self.detalle = "Especificamente, almacena datos de varios tipos (Segun soporte Python)."

    def getTitulo(self):
        return self.titulo

    def getDesc(self):
        return self.desc

    def getDetalle(self):
        return self.detalle

pos = 1
seguir = 1
n = Nodo(pos)
c = Nodo(pos)

n.setElemento(raw_input("Ingrese su primer dato: "))
while(seguir):
    pos += 1
    opc = raw_input("Desea ingresar otro dato? S/N ")
    if(opc == 'S'):
        a = Nodo(pos)
        n.setSiguiente(a)
        a.setElemento(raw_input("Ingrese el otro dato: "))
        if(c.getSiguiente==''):
            c=n
        n=a
    else:
        seguir = 0

for i in range (1,pos):
    print(c.getInfo())
    print("El nodo almacena: "+c.getElemento())
    
asked by Josue 01.10.2018 в 08:27
source

1 answer

1

First, you have complicated, I believe unnecessarily when creating the nodes in the while , the comparison if(c.getSiguiente=='') is not necessary, you can simply use a variable before the cycle to keep the reference to the first node and not modify it ever But, in addition, you do not call the method, you are missing the parentheses, ( if c.getSiguiente() == '' ) so it is always False being c a Nodo empty and therefore losing all references to the root node.

However, the real problem is that, as is your implementation, it is impossible to use the position to iterate over the list. The only way to do this is to start from the root node and use the siguiente attribute to obtain the next element, worth the redundancy. You can not iterate backwards because you do not store your predecessor in each node.

An observation, you should not initialize self.siguiente to an empty string, siguiente is going to be an instance of Nodo , never a string. Use None for this. On the other hand, when you want to know if a string is empty (or any container) do not use if cadena == "" , just do if cadena:

Your code might look something like this:

# Creación de la lista
pos = 1

nodo_raiz = Nodo(pos)
nodo_raiz.setElemento(raw_input("Ingrese su primer dato: "))
ultimo_nodo = nodo_raiz

while True:
    pos += 1
    opc = raw_input("Desea ingresar otro dato? S/N ")
    if opc.lower() == 's':
        nuevo_nodo = Nodo(pos)
        nuevo_nodo.setElemento(raw_input("Ingrese el otro dato: "))
        ultimo_nodo.setSiguiente(nuevo_nodo)
        ultimo_nodo = nuevo_nodo
    else:
        break

# Iterando partiendo del nodo raiz
nodo = nodo_raiz
while nodo is not None:
    print(nodo.getInfo())
    print("El nodo almacena: {}".format(nodo.getElemento()))
    nodo = nodo.getSiguiente() 
  

Remember to change self._siguiente = '' by self._siguiente = None in the initializer of class Nodo .

On the other hand, although it is not an error in itself, in Python the concept of "getter" and "setter" does not exist, you can directly access the attributes without problems. If you want functionality similar to a "getter" or "setter" (such as validation) the Python alternative is the data descriptors ( properties ). This would be a version of your code making use of them, in case you are interested in the topic:

class Nodo:
    def __init__(self, pos):
        self._siguiente = None
        self._pos = None
        self._elemento = ''
        self.pos = pos
        self._info = NodoInfo(self.pos)

    @property
    def siguiente(self):
        return self._siguiente

    @siguiente.setter
    def siguiente(self, n):
        self._siguiente = n

    @property
    def pos(self):
        return self._pos

    @pos.setter
    def pos(self, pos):
        self._pos = pos

    @property
    def elemento(self):
        return self._elemento

    @elemento.setter
    def elemento(self,a):
         self._elemento = a

    @property
    def info(self):
        return self._info.titulo



class NodoInfo:
    def __init__(self, pos):
        self._titulo = "Numero de nodo: {}".format(pos)
        self._desc = "Este nodo puede almacenar datos."
        self._detalle = "Especificamente, almacena datos de varios tipos (Segun soporte Python)."

    @property
    def titulo(self):
        return self._titulo

    @property
    def desc(self):
        return self._desc

    @property
    def detalle(self):
        return self._detalle



pos = 1

nodo_raiz = Nodo(pos)
nodo_raiz.elemento = raw_input("Ingrese su primer dato: ")
ultimo_nodo = nodo_raiz

while True:
    pos += 1
    opc = raw_input("Desea ingresar otro dato? S/N ")
    if opc.lower() == 's':
        nuevo_nodo = Nodo(pos)
        nuevo_nodo.elemento = raw_input("Ingrese el otro dato: ")
        ultimo_nodo.siguiente = nuevo_nodo
        ultimo_nodo = nuevo_nodo
    else:
        break


nodo = nodo_raiz
while nodo is not None:
    print(nodo.info)
    print("El nodo almacena: {}".format(nodo.elemento))
    nodo = nodo.siguiente 
    
answered by 01.10.2018 в 10:19