Doubt with matrix
Peter Otten
__peter__ at web.de
Thu Jan 12 11:59:31 EST 2017
José Manuel Suárez Sierra wrote:
> Hello, I want to go over matrix indexs with this code:
> def comparador2(a, b):
> c3 = ["0"] # variables
> x = -1 # contador de letras aniadidas a c3
> i = 0 # contador bucle secuencia a
> j = 0 # contador bucle secuencia b
> l1 = len(a)
> l2 = len(b)
> cont = [] # contador de ciclos poner primer termino a 0
> k = -1 # contador de 0 y 1 aniadidos a cont
>
> if l1 > l2: # metodo de la burbuja que elige la secuencia mas larga
> REVISAR puede ser alreves
In Python there's a cool way to swap values without an explicit helper
variable:
a, b = b, a
> aux = a
> a = b
> b = aux
OK, now you have swapped a and b, but not their respective lengths l1 and
l2...
> for a[i] in a: # en la secuencia1 recorro los elementos
Do you really want to modify a[i] on every iteration? Most certainly not.
Try to use the normal way with just a name, e. g.
for entry_a in a:
...
Then use entry_a instead of a[i] for your comparison in the body of the for-
loop. With that approach it's impossible to get an IndexError.
If you still need the index to alter an entry in the list -- enumerate() is
your friend:
for index_a, entry_a in enumerate(a):
...
Again it's unlikely that you will get an IndexError.
> for b[j] in b :
>
> if a[i] == b[j] and i <= l1 and j <= l2: # Si el elemento
> i de la seq1 es igual que el elemento j de la seq2, y el
> numero de elementos en i y j es menor o igual que la
> longitud de las secuencias 1 y 2
> c3.append(a[i]) # se aniade el elemento comun a la
> lista c3 x = x + 1
> k = k + 1
> j = j + 1 # se pasa el elemento siguiente de la seq2
> i = i + 1 # se pasa el elemento siguiente de la seq1
> cont.append(1)
>
>
>
> elif a[i] != b[
> j] and i <= l1 and j <= l2: # si no coinciden estos
> elementos se pasa al siguiente elemento de la lista 2
> j = j + 1 k = k + 1
> cont.append(0)
> if cont[k] == 0 and cont[k - 1] == 1 and cont[k - 2]
> == 0 and k >= 2:
> i = i - 1
> j = j - 1
> else:
> k = k + 1
> cont.append(0)
> if i == l2:
> i = i + 1
> j = 0
>
>
> return c3
>
> and this issue is prompted:
> IndexError: list assignment index out of range
>
> How could I fix it?
>
> Thank you for your assistance
More information about the Python-list
mailing list