Infinite generator - Cycle and Sum
Working through a python example and presented with the problem
Write a one-line Python generator or iterator expression that returns the infinite sequence of increasing integers generated by repeatedly adding the ascii values of each letter in the word “Close” to itself. 67, 175, 286, 401, 502, 569, 677, 788, 903 is the beginning of this sequence. Assume any needed Python standard library modules are already imported.
I came up with this, which is
- Take each letter in the word
Close
- Find the ordinal value of that letter i.e.
C
=67
- Cycle over the values as a generator using
itertools.cycle
- Then accumulate the values as another iterator adding each value
itertools.accumulate
Code
import itertools
import operator
import time
if __name__ == '__main__':
my_gen = (itertools.accumulate(itertools.cycle((ord(letter) for letter in 'Close'))))
for current_value in itertools.islice(my_gen, 12):
print(current_value)
Results
67
175
286
401
502
569
677
788
903
1004
1071
1179
Bonus
Any word format as a function
def infinite_generator(input_word: str) -> Iterator[int]:
return itertools.accumulate(itertools.cycle((ord(letter) for letter in input_word)))