This code fails:
fCamel = 'F'
bCamel = 'B'
gap = ' '
k = ['F', ' ', 'B', 'F']
def solution(formation):
return ((formation.index(bCamel) > (len(formation) - 1 - (formation.reverse()).index(fCamel))))
solution(k)
I get an exception that says AttributeError: 'NoneType' object has no attribute 'index'
.
I know that the problem is that list.reverse()
returns None
, modifying the list in-place. I want to use .index
on the reversed list. Is there a way I can avoid using a separate statement to reverse the list before indexing into it? How?
You can use reversed(formation)
to return a reverse iterator of formation
. When you call formation.reverse()
it does an in place reversal of the list and returns None.
EDIT:
I see what you are trying to do now, in my opinion it's easier to just do this with a list comprehension:
def solution(formation):
return len([k for k in formation[formation.index(bCamel)+1:] if k == fCamel]) == 0
This basically looks at all the elements after the first bCamel
and collects all the elements that have the value fCamel
. If that list has a length == 0 you have a solution.
Here's a few examples:
>>> k = ['F','F','B','B','F']
>>> solution(k)
False
>>> k = ['F','F','B','B','B']
>>> solution(k)
True
>>> k = ['F','F','B','F','F','B','B']
>>> solution(k)
False
>>>