1. #!/usr/bin/python
  2.  
  3. from go import *
  4.  
  5. # Problem: process just the numbers in the following....
  6.  
  7. x = ["a",
  8. [],
  9. 1,
  10. 2,
  11. [ "b",
  12. 3,
  13. 4
  14. ]
  15. ]
  16.  
  17. def nump(x):
  18. return isinstance(x, (int, long, float, complex))
  19.  
  20. # Solutions
  21.  
  22. # 1111111111
  23. # Solution #1: pass around a lambda body
  24.  
  25. def rwalk(thing,f,tmp):
  26. if isinstance(thing,list):
  27. for any in thing:
  28. tmp = rwalk(any,f,tmp)
  29. else:
  30. tmp = f(tmp,thing)
  31. return tmp
  32.  
  33.  
  34. def rSum(x):
  35. def worker(old,new):
  36. return old+new if nump(new) else old
  37. return rwalk(x,worker,0)
  38.  
  39. @go
  40. def _rSum(): print rSum(x)
  41.  
  42. def rKeep(x):
  43. def worker(lst,new):
  44. if nump(new): lst += [new]
  45. return lst
  46. return rwalk(x,worker,[])
  47.  
  48. @go
  49. def _rKeep(): print rKeep(x)
  50.  
  51.  
  52. # 222222222
  53. # Solution #2: iterators
  54.  
  55. def rItems(thing):
  56. if isinstance(thing,list):
  57. for any in thing:
  58. for one in rItems(any):
  59. yield one
  60. else:
  61. yield thing
  62. @go
  63. def _recursiveAdd():
  64. n = 0
  65. for i in rItems(x):
  66. if nump(i):
  67. n += i
  68. print n
  69.  
  70. @go
  71. def _recursiveAccum():
  72. out = []
  73. for i in rItems(x):
  74. if nump(i):
  75. out += [i]
  76. print out