0
def troca_valor(lista, i1, i2):
    a = lista[:]
    tam = len(lista)
    if i1 or i2 > tam:
        return None
    else:
        a[i1] = lista[i2]
        a[i2] = lista[i1]
        return a

assert troca_valor([0,1,2,3],2,0) == [2,1,0,3]
assert troca_valor(["a", "e", "i", "o", "u"],1,3) == ["a", "o", "i","e", "u"]
assert troca_valor([0,1,2,3],7,3) == None
assert troca_valor([0,1,2,3],2,5) == None

I have to change the values at the list change one position per another, like in the asserts, i'm trying to do something like this code but shows a assert error. This is my first ask, i use the search but didn't fing any similar questions. Sorry for my english.

  • 1
    Look closely at `i1 or i2 > tam`; Python doesn't see that as i1 greater than tam or i2 greater than tam; it sees that as `i1` is true or `i2 > tam`. And in your first assert `i1` is 2, which means it is a true value. – Martijn Pieters Oct 15 '13 at 23:21
  • thank you, sorry for a silly question, but i really don't know. –  Oct 15 '13 at 23:30

1 Answers1

1

I think you're misunderstanding the or operator. Python first evaluates the truthfulness of i1. If it is true (in your case, non-zero), then python executes that block without ever looking at the second condition. What you really want is for the first condition to also check if the index is valid for the list. i.e. It should be:

if i1 > tam or i2 > tam:
   ...

Also, as an aside, a common idiom for swapping elments in python is:

a, b = b, a

So, a working version of your code could look like this:

def troca_valor(lista, i1, i2):
    a = lista[:]
    tam = len(lista)
    if i1 > tam or i2 > tam:
        return None
    else:
        a[i1], a[i2] = lista[i2], lista[i1]
        return a

assert troca_valor([0,1,2,3],2,0) == [2,1,0,3]
assert troca_valor(["a", "e", "i", "o", "u"],1,3) == ["a", "o", "i","e", "u"]
assert troca_valor([0,1,2,3],7,3) == None
assert troca_valor([0,1,2,3],2,5) == None
mgilson
  • 300,191
  • 65
  • 633
  • 696