Browse Source

add deque example in Python

master
Charles Reid 5 years ago
parent
commit
2239877924
  1. 21
      python/README.md
  2. 34
      python/UseDeque.py

21
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.

34
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
Loading…
Cancel
Save