I have the following function, which produces a sequence of numbers. I would like to turn it into a one-liner in the form of an iterator or a generator. How can I do that?
def one_line_generator():
sum = 0
string = "Hello"
i = 0
while True:
sum = ord(string[i])
yield sum
if i<len(string)-1:
i = 1
else:
i = 0
CodePudding user response:
Another try
from itertools import accumulate, cycle
from operator import add
string = "Hello"
res = accumulate(cycle(map(ord, string)), add)
CodePudding user response:
Like so, for instance, if you insist.
import itertools
def oneline2(string, i=0):
return itertools.chain.from_iterable(((i := i ord(c)) for c in s) for s in itertools.repeat(string))