is there a better way?
Carl Friedrich Bolz
cfbolz at gmx.de
Fri Feb 10 14:46:06 EST 2006
Hi!
markscala at gmail.com wrote:
> Problem:
>
> You have a list of unknown length, such as this: list =
> [X,X,X,O,O,O,O]. You want to extract all and only the X's. You know
> the X's are all up front and you know that the item after the last X is
> an O, or that the list ends with an X. There are never O's between
> X's.
>
> I have been using something like this:
> _____________________
>
> while list[0] != O:
> storage.append(list[0])
> list.pop(0)
> if len(list) == 0:
> break
> _____________________
>
> But this seems ugly to me, and using "while" give me the heebies. Is
> there a better approach?
Depends on what you mean with "better". I (heavily inspired by the
bisect module) came up with:
low = 0
high = len(L)
while low < high:
mid = (low + high) // 2
if L[mid] == 0:
high = mid
else:
low = mid + 1
storage = L[:low]
This has the advantage to be more efficient compared to other
approaches, which of course only matters if your list is big. It still
features a "while" loop, though.
> hope this is clear.
It is not entirely clear what the X is supposed to be. I assumed that it
can be anything except 0.
Cheers,
Carl Friedrich
More information about the Python-list
mailing list