diff --git a/python/README.md b/python/README.md index bfd3e92..e23c8c5 100644 --- a/python/README.md +++ b/python/README.md @@ -40,7 +40,26 @@ Key functionality: ## Python Binary Array Tree -Array implementation of the binary tree, in lieu of the Node plus point er concept. +Array implementation of the binary tree, in lieu of the Node plus pointer concept. This is kind of like the way we do it in Perl. +## Zoo + +The zoo exhibits basic behaviors of some built-in collection types in Python. +Why roll your own when you can use a standard library? + +## UseDeque + +This script shows the use of a deque (double-ended queue) to pop items front-to-back or back-to-front, switching direction occasionally. + + + + + + + + + + + diff --git a/python/UseDeque.py b/python/UseDeque.py new file mode 100644 index 0000000..81f4acb --- /dev/null +++ b/python/UseDeque.py @@ -0,0 +1,34 @@ +from collections import deque +import random + +# Populate empty deck with integers 1 to 10 +d = deque() +n = 10 +for i in range(n): + d.append(i+1) + +print("Initial deque:") +print(d) + +# Note you can also rotate the dequeue: +d.rotate(2) +d.rotate(-2) + +# Pop from the list, +# moving from the front of the list (right) to the back of the list (left). +# If a random event happens, we switch directions and pop from the back (left). + +print("Popping:") +move_forward = True +while d: + if(move_forward): + nxt = d.pop() + print("Moving forward: %s"%(nxt)) + else: + nxt = d.popleft() + print("Moving backward: %s"%(nxt)) + + # 70% chance that we continue moving forward + if( random.random() < 0.7 ): + move_forward = not move_forward +