#! /usr/bin/env python class linked_list(): class node(): def __init__(self, data=None): self.data = data self.next = None def __str__(self): return str(data) class list_iterator(): def __init__(self, current_node=None): self.current_node = current_node def hasNext(self): return self.current_node.next is not None def next(self): if not self.hasNext(): return None self.current_node = self.current_node.next; return self.current_node.data; def __init__(self): self.head = None self._size = 0 def iterator(self): return self.list_iterator(self.head) def is_empty(self): return self.head is None def size(self): return self._size def insert_after(self, data, index): new_node = self.node(data) curr_node = self.head i = 0 while curr_node is not None and i < index: curr_node = curr_node.next i += 1 new_node.next = curr_node.next curr_node.next = new_node self._size += 1 def insert_beginning(self, data): new_node = self.node(data) if self.is_empty(): self.head = new_node else: new_node.next = self.head self.head = new_node self._size += 1 def insert_end(self, data): new_node = self.node(data) if self.is_empty(): self.head = new_node else: curr_node = self.head while curr_node.next is not None: curr_node = curr_node.next curr_node.next = new_node self._size += 1 def filter_reduce(self, reduce_func, filter_func=None, initializer=None): it = self.iterator() if initializer is None: try: initializer = it.next() except StopIteration: raise TypeError('reduce() of empty sequence with no initial value') accum_value = initializer while it.hasNext(): data = it.next() if filter_func is None or filter_func(data): accum_value = reduce_func(accum_value, data) return accum_value def __str__(self): s, it = '', self.iterator() while it.hasNext(): s += str(it.next()) if it.hasNext(): s += ', ' return s """ Output: ======================= List: 1, 2, 3, 4, 5 Size: 6 Summation: 9 Product: 1200 ======================= """ if __name__ == '__main__': def calc_product(a, b): return a * b def calc_summation(a, b): return a + b def is_odd(x): return x % 2 != 0 l = linked_list() l.insert_end(1) l.insert_end(2) l.insert_end(3) l.insert_end(5) l.insert_beginning(0) l.insert_after(4, 3) print 'List:', l print 'Size:', l.size() # Calculates the sum of all odd values in the list: print 'Summation:', l.filter_reduce(calc_summation, is_odd) # Calculates the product of all values with the accumulator # initialized at 10. print 'Product:', l.filter_reduce(calc_product, lambda x: True, 10)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question