question about a program
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Oct 8 22:01:32 EDT 2010
On Thu, 07 Oct 2010 17:39:51 -0700, Logan Butler wrote:
> question about an assignment:
>
>>>> places("home sweet home is here",' ')
> [4, 10, 15, 18]
>
> this is my code:
>
> def places(x, y):
> return [x.index(y) for v in x if (v == y)]
>
> so far I'm only getting
> [4, 4, 4, 4]
>
> so the first value is correct, it is just not iterating on to the next
> three items it needs to
Not every tool is a hammer, not every list builder needs to be a list
comp, and not every function needs to be a one-liner. The simplest way to
deal with this is to do an explicit loop.
Also, your names "x" and "y" are misleading. It is conventional to expect
x and y to be numeric values, so it is best to pick more descriptive
names.
def places(s, sub):
"""Return indexes into string s where non-overlapping copies
of substring sub is found, or [-1] if not found at all.
"""
n = len(sub)
start = 0
indexes = []
try:
while True:
i = s.index(sub, start)
indexes.append(i)
start = i + n
except ValueError:
if not indexes: indexes = [-1]
return indexes
--
Steven
More information about the Python-list
mailing list