/Demo/threads/fcmp.py

http://unladen-swallow.googlecode.com/ · Python · 64 lines · 52 code · 7 blank · 5 comment · 14 complexity · 6bf1855c55855eb59d00c14af2e2a21d MD5 · raw file

  1. # Coroutine example: controlling multiple instances of a single function
  2. from Coroutine import *
  3. # fringe visits a nested list in inorder, and detaches for each non-list
  4. # element; raises EarlyExit after the list is exhausted
  5. def fringe(co, list):
  6. for x in list:
  7. if type(x) is type([]):
  8. fringe(co, x)
  9. else:
  10. co.back(x)
  11. def printinorder(list):
  12. co = Coroutine()
  13. f = co.create(fringe, co, list)
  14. try:
  15. while 1:
  16. print co.tran(f),
  17. except EarlyExit:
  18. pass
  19. print
  20. printinorder([1,2,3]) # 1 2 3
  21. printinorder([[[[1,[2]]],3]]) # ditto
  22. x = [0, 1, [2, [3]], [4,5], [[[6]]] ]
  23. printinorder(x) # 0 1 2 3 4 5 6
  24. # fcmp lexicographically compares the fringes of two nested lists
  25. def fcmp(l1, l2):
  26. co1 = Coroutine(); f1 = co1.create(fringe, co1, l1)
  27. co2 = Coroutine(); f2 = co2.create(fringe, co2, l2)
  28. while 1:
  29. try:
  30. v1 = co1.tran(f1)
  31. except EarlyExit:
  32. try:
  33. v2 = co2.tran(f2)
  34. except EarlyExit:
  35. return 0
  36. co2.kill()
  37. return -1
  38. try:
  39. v2 = co2.tran(f2)
  40. except EarlyExit:
  41. co1.kill()
  42. return 1
  43. if v1 != v2:
  44. co1.kill(); co2.kill()
  45. return cmp(v1,v2)
  46. print fcmp(range(7), x) # 0; fringes are equal
  47. print fcmp(range(6), x) # -1; 1st list ends early
  48. print fcmp(x, range(6)) # 1; 2nd list ends early
  49. print fcmp(range(8), x) # 1; 2nd list ends early
  50. print fcmp(x, range(8)) # -1; 1st list ends early
  51. print fcmp([1,[[2],8]],
  52. [[[1],2],8]) # 0
  53. print fcmp([1,[[3],8]],
  54. [[[1],2],8]) # 1
  55. print fcmp([1,[[2],8]],
  56. [[[1],2],9]) # -1
  57. # end of example