Момчил обнови решението на 03.04.2015 08:21 (преди над 9 години)
+def fibonacci():
+ previous = 0
+ number = 1
+ while True:
+ current = number
+ yield number
+ number += previous
+ previous = current
+
+
+def is_prime(number):
+ counter = 0
+ for i in range(2, number):
+ if number % i == 0:
+ counter += 1
+ return counter == 0
+
+
+def primes():
+ i = 2
+ while True:
+ if is_prime(i):
+ yield i
+ i += 1
+
+
+def alphabet(**kwargs):
+ if 'letters' in kwargs:
+ for letter in kwargs['letters']:
+ ch = letter
+ yield ch
+ elif kwargs['code'] == 'lat':
+ ch = 'a'
+ while ch <= 'z':
+ yield ch
+ ch = chr(ord(ch) + 1)
+ elif kwargs['code'] == 'bg':
+ ch = 'а'
+ while ch <= 'я':
+ yield ch
+ ch = chr(ord(ch) + 1)
+
+
+def intertwined_sequences(iterable, **kwargs):
+ generators = {}
+ for iteration in iterable:
+ if iteration['sequence'] not in generators:
+ if iteration['sequence'] == 'fibonacci':
+ generators[iteration['sequence']] = fibonacci()
+ elif iteration['sequence'] == 'primes':
+ generators[iteration['sequence']] = primes()
+ elif 'letters' in iteration:
+ generators[iteration['sequence']] = alphabet(
+ letters=iteration['letters'])
+ elif 'code' in iteration:
+ generators[iteration['sequence']] = alphabet(
+ code=iteration['code'])
+ elif ('generator_definitions' in kwargs and
+ iteration['sequence'] in kwargs['generator_definitions']):
+ generators[iteration['sequence']] = iter(
+ kwargs['generator_definitions'][iteration['sequence']](
+ **kwargs))
+ for iteration in iterable:
+ counter = iteration['length']
+ while counter > 0:
+ res = next(generators[iteration['sequence']])
+ yield res
+ counter -= 1
iterable
може да бъде безкраен, което ще рече, че още първия for
на intertwined_sequences
никога няма да приключи, за да се стигне до втория, който yield-ва.