Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As @Cybis and others mentioned, you can't keep the O(N) complexity with Python lists; you'll have to create a linked list. At the risk of proving <a href="http://en.wikipedia.org/wiki/Greenspun%27s_Tenth_Rule" rel="nofollow noreferrer">Greenspun's 10th rule</a>, here is such a solution:</p> <pre><code>class cons(tuple): __slots__=() def __new__(cls, car, cdr): return tuple.__new__(cls, (car,cdr)) @classmethod def from_seq(class_, l): result = None for el in reversed(l): result = cons(el, result) return result @property def car(self): return self._getitem(0) @property def cdr(self): return self._getitem(1) def _getitem(self, i): return tuple.__getitem__(self, i) def __repr__(self): return '(%s %r)' % (self.car, self.cdr) def __iter__(self): v = self while v is not None: yield v.car v = v.cdr def __len__(self): return sum(1 for x in self) def __getitem__(self, i): v = self while i &gt; 0: v = v.cdr i -= 1 return v.car def maplist(func, values): result = [ ] while values is not None: result.append(func(values)) values = values.cdr return result </code></pre> <p>Testing yields:</p> <pre><code>&gt;&gt;&gt; l = cons.from_seq([1,2,3,4]) &gt;&gt;&gt; print l (1 (2 (3 (4 None)))) &gt;&gt;&gt; print list(l) [1, 2, 3, 4] &gt;&gt;&gt; print maplistr(lambda l: list(reversed(l)), cons.from_seq([1,2,3])) [[3, 2, 1], [3, 2], [3]] </code></pre> <p>EDIT: Here is a generator-based solution that basically solves the same problem without the use of linked lists:</p> <pre><code>import itertools def mapiter(func, iter_): while True: iter_, iter2 = itertools.tee(iter_) iter_.next() yield func(iter2) </code></pre> <p>Testing yields:</p> <pre><code>&gt;&gt;&gt; print list(mapiter(lambda l: list(reversed(list(l))), [1,2,3])) [[3, 2, 1], [3, 2], [3]] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload