Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #50404
| References | <CAPTjJmpmYZ3PG1Eoi3DYk1TYWHqZT222vue889=LnU687wTwcA@mail.gmail.com> |
|---|---|
| From | Joshua Landau <joshua@landau.ws> |
| Date | 2013-07-11 03:37 +0100 |
| Subject | Re: Stupid ways to spell simple code |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.4557.1373510291.3114.python-list@python.org> (permalink) |
On 30 June 2013 07:06, Chris Angelico <rosuav@gmail.com> wrote:
> So, here's a challenge: Come up with something really simple, and
> write an insanely complicated - yet perfectly valid - way to achieve
> the same thing. Bonus points for horribly abusing Python's clean
> syntax in the process.
This occurred to me out of the blue while working on something
related. Here's a way to remove all instances of an element from an
iterable. It's remarkably fast for it's course of action:
from collections import deque
from itertools import chain
exhaust_iterable = deque(maxlen=0).extend
def split_on(data, sentinel):
chained = data = iter(data)
while True:
chunk = iter(chained.__next__, sentinel)
yield chunk
# Uses at least one item from chained, so "chained" and
"data" are equivilant after this.
# This is important as "data" is raw and thus will not get
bogged down by pointless chain wrappings.
# Yes, that is a premature optimisation. Go away.
exhaust_iterable(chunk)
# Throw StopIteration if not empty
chained = chain([next(data)], data)
def remove_all(iterable, victim):
return list(chain.from_iterable(split_on(iterable, victim)))
print(remove_all([1, 2, 1, 1, 0, 1, 2, 1, 1, 2, 2, 1, 0], 1))
and here it is again:
from itertools import chain, repeat
def remove_all(iterable, victim):
iterable = iter(iterable)
return list(chain.from_iterable(iter(chain([next(iterable)],
iterable).__next__, victim) for _ in repeat(...)))
print(remove_all([1, 2, 1, 1, 0, 1, 2, 1, 1, 2, 2, 1, 0], 1))
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Stupid ways to spell simple code Joshua Landau <joshua@landau.ws> - 2013-07-11 03:37 +0100
csiph-web