vegaseat

circular sequence generator

Mar 13th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. ''' circular_sequence_generator3.py
  2. can be replaced with itertools.cycle()
  3.  
  4. with Python25 use f.next()
  5. with Python26 and higher use next(f)
  6. '''
  7.  
  8. # allows Python27 to use Python3 print() options
  9. from __future__ import print_function
  10. import itertools
  11.  
  12. def circular_sequence_gen(seq=""):
  13.     '''
  14.    generic circular sequence generator
  15.    '''
  16.     i = 0
  17.     while True:
  18.         yield seq[i]
  19.         i = (i + 1)%len(seq)
  20.  
  21. # testing ...
  22. mystr = 'abc'
  23.  
  24. for count, c in enumerate(circular_sequence_gen(mystr)):
  25.    print(c, end="")
  26.    if count >= 20:
  27.        break
  28.  
  29. print('')
  30.  
  31. for count, c in enumerate(itertools.cycle(mystr)):
  32.    print(c, end="")
  33.    if count >= 20:
  34.        break
  35.  
  36. print('')
  37.  
  38. colors = ['red', 'blue', 'green', 'orange']
  39.  
  40. color_gen = circular_sequence_gen(colors)
  41.  
  42. for color in range(12):
  43.     # Python26 and up
  44.     print(next(color_gen))
  45.  
  46. print('-'*20)
  47.  
  48. color_gen = itertools.cycle(colors)
  49.  
  50. for color in range(12):
  51.     # Python26 and up
  52.     print(next(color_gen))
  53.  
  54. ''' result -->
  55. abcabcabcabcabcabcabc
  56. abcabcabcabcabcabcabc
  57. red
  58. blue
  59. green
  60. orange
  61. red
  62. blue
  63. green
  64. orange
  65. red
  66. blue
  67. green
  68. orange
  69. --------------------
  70. red
  71. blue
  72. green
  73. orange
  74. red
  75. blue
  76. green
  77. orange
  78. red
  79. blue
  80. green
  81. orange
  82. '''
Advertisement
Add Comment
Please, Sign In to add comment