Browse Source

Initial commit

R. Alex Matevish 5 years ago
commit
feca7151da
4 changed files with 86 additions and 0 deletions
  1. 41 0
      example.py
  2. 15 0
      fig1.c
  3. 15 0
      fig2.py
  4. 15 0
      fig3.py

+ 41 - 0
example.py

@@ -0,0 +1,41 @@
+from itertools import chain
+
+
+class BinaryTreeNode(object):
+
+  def __init__(self, value):
+    self.value = value
+    self.left = None
+    self.right = None
+
+  def set_left(self, node):
+    self.left = node
+    return self  # return self so we can chain calls
+
+  def set_right(self, node):
+    self.right = node
+    return self  # return self so we can chain calls
+
+  def __str__(self):
+    return "<%d: %s, %s>" % (self.value, str(self.left), str(self.right))
+
+
+class IteratingBinaryTreeNode(BinaryTreeNode):
+
+  def __iter__(self):
+    left = self.left or []
+    right = self.right or []
+    return chain(iter(left), iter([self.value]), iter(right))
+
+
+if __name__ == "__main__":
+  tree = BinaryTreeNode(1).set_left(BinaryTreeNode(0)).set_right(BinaryTreeNode(2))
+  print tree
+
+  iter_tree = (IteratingBinaryTreeNode(4) # Root
+                .set_left(IteratingBinaryTreeNode(2) # L
+                  .set_left(IteratingBinaryTreeNode(1)) # L L
+                  .set_right(IteratingBinaryTreeNode(3))) # L R
+                .set_right(IteratingBinaryTreeNode(5) # R L
+                  .set_right(IteratingBinaryTreeNode(6)))) # R R
+  print list(iter(iter_tree))

+ 15 - 0
fig1.c

@@ -0,0 +1,15 @@
+#include<stdio.h>
+#include<stddef.h>
+
+// Compile with `gcc -Wall -pedantic -ansi -std=c99 fig1.c`
+
+int main() {
+    // Define an array of strings
+    char myStrings[][10] = {"one", "two", "three", "four", "five"};
+
+    // Print strings in array, from 0 -> |length of myStrings (4)|
+    size_t i = 0;
+    for (i = 0; i < 5; i++) {
+        printf("%s\n", myStrings[i]);
+    }
+}

+ 15 - 0
fig2.py

@@ -0,0 +1,15 @@
+class Iterable(object):
+  def __init__(self):
+    self.arr = range(10)
+
+  def __iter__(self):
+    return iter(self.arr)
+
+  def __getitem__(self, index):
+    """ If Python tried to iterate with this method we'd be stuck in an infinite loop (because `__getitem__` never raises an `IndexError`) """
+    return self.arr[0]
+
+
+if __name__ == "__main__":
+    # Prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+    print [i for i in Iterable()]

+ 15 - 0
fig3.py

@@ -0,0 +1,15 @@
+class Iterable(object):
+  def __init__(self):
+    self.arr = range(10)
+
+  def __iter__(self):
+    # This iterable returns *itself* as the iterator, and keeps track of
+    # where it is with a private variable (indicated by the underscore)
+    self._current_index = 0
+    return self
+
+  def __next__(self):
+     # Get item and update which index we're returning next
+     item = self.arr[self._current_index]
+     self._current_index += 1
+     return item