-1

Ok so I am currently making a program that takes out every instant of the number 3 from an array/list.

You can see below an example of when the array has an uneven amount of indexes.

o =[1,2,3]
b = 3
def remove(b,o):
    while o!= []:
        if b == o[0]:
            s = [o[1]] + remove(b,o[2:])
            return s
        else:
           ss = [o[0]] + remove(b,o[1:])
           return ss
    if o==[]:
        return o
print remove(b,o)

It should just print out [1,2] but it crashes.

asongtoruin
  • 9,794
  • 3
  • 36
  • 47
joe9123a
  • 11
  • 1
  • What is the `error log`? – Kaushik NP Oct 23 '17 at 11:11
  • 1
    you should try writing out by hand what is happening when your list is passed through the function - it should become clear where the issue is – asongtoruin Oct 23 '17 at 11:17
  • @KaushikNP s = [o[1]] + remove(b,o[2:]) IndexError: list index out of range – joe9123a Oct 23 '17 at 11:17
  • 1
    This must be one of the most complicated ways of doing this. – Hannu Oct 23 '17 at 11:18
  • 2
    https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list gives some ideas of the more Pythonic ways of doing this. Or you can just do o.remove() in an infinite loop until it raises a ValueError indicating there are no more occurrences of your value in the list. – Hannu Oct 23 '17 at 11:21

2 Answers2

1

Adding a print statement like this:

def remove(b,o):
    while o!= []:
        print(o)
        if b == o[0]:
            s = [o[1]] + remove(b,o[2:])
            return s
        else:
           ss = [o[0]] + remove(b,o[1:])
           return ss
    if o==[]:
        return o

Quickly locates the problem.

[1, 2, 3]
[2, 3]
[3]

When it gets to the 3, there is only one element in o, so o[1] raises an IndexError. Also, it shouldn't even add o[1] directly to the list, since that might be a 3.

Also, there is no point in having the loop or the second if statement, since it won't run more than once anyway. And there are faster ways to do this than adding lists.

Putting it all together, here's one solution that aims to keep your existing algorithm intact (there are of course better and more efficient ways of doing this):

def remove(b,o):
    if o == []:
        return []
    s = remove(b, o[1:])
    if b != o[0]:
       s.insert(0, o[0])
    return s
anonymoose
  • 819
  • 2
  • 11
  • 25
-1

Try this. x = filter(lambda a: a != 3, o)

You can save yourself the trouble of writing that function which crashes when the elements in the list are odd.

Cyrille Pontvieux
  • 2,356
  • 1
  • 21
  • 29