Possible Duplicate:
How to make a function that counts how many times each element is equal to 2 elements to its right
I need help with the prompt below. For some reason I keep on getting a "'int' object is not subscriptable" errpr and don't really know how to fix it. I have a feeling that it has something to do with my helper function.
Here are the Tests:
'''
skip(X) counts how many times an item in
sequence X is equal to the item
"two places to the right" in X.
Examples:
skip("evening") is 2, once
for 'e' and once for 'n'
skipt([1,2,3,4]) is 0
skipt([0,0,0,0,0]) is 3, because
there are five 0's, but
the last two can't be
compared to item two places
to the right.
>>> X = "onoratitatio"
>>> skip(X)
3
>>> Y = 2*[3,1]+4*[1,5]
>>> skip(Y)
8
>>> skip([5])
0
'''
Here is what I have currently created:
def helper(X):
return X[0] == X[2]
def skip(X):
return len(filter(helper,X))
I don't really know, but I'm about fed up w开发者_运维技巧ith this problem. Does anyone have any ideas?
In [4]: word = "mississippi"
In [5]: word_list = [w for w in xrange(len(word) - 2) if word[w] == word[w + 2]]
In [6]: print len(word_list)
1
In [7]: word = "evening"
In [8]: word_list = [w for w in xrange(len(word) - 2) if word[w] == word[w + 2]]
In [9]: print len(word_list)
2
You can't do this with filter()
, because filter
takes a single value from an iterable and has no way to know the whole iterable you are trying to test.
What @chown is trying to tell you is that you can fix skip()
by using the same answer your classmate got...
def skip(X):
return len([w for w in xrange(len(X) - 2) if X[w] == X[w + 2]])
Explicitly...
>>> def skip(X):
... return len([w for w in xrange(len(X) - 2) if X[w] == X[w + 2]])
...
>>> skip('evening')
2
>>> skip([1,2,3,4])
0
>>> skip([0,0,0,0,0])
3
>>> skip("onoratitatio")
3
>>>
精彩评论