Елена обнови решението на 03.04.2015 02:15 (преди над 9 години)
+def fibonacci():
+ first, second = 1, 1
+ while True:
+ yield first
+ first, second = second, first + second
+
+
+def primes():
+ yield 2
+ n = 2
+ while True:
+ n += 1
+ for p in primes():
+ if p * p > n:
+ yield n
+ break
+ if (n % p) == 0:
+ break
+
+
+def alphabet(code=None, letters=None):
+ if code == 'lat' and not letters:
+ lat_letters = list(map(chr, range(97, 123)))
+ iterator = iter(lat_letters)
+ length = len(lat_letters)
+ if code == 'bg' and not letters:
+ bg_letters = list(map(chr, range(1072, 1103)))
+ iterator = iter(bg_letters)
+ length = len(bg_letters)
+ if letters:
+ iterator = iter(letters)
+ length = len(letters)
+ i = 0
+ while i < length:
+ yield next(iterator)
+ i += 1
+ raise StopIteration
+
+
+def intertwined_sequences(generators, generator_definitions={}):
+ fibonacci_seq = fibonacci()
+ primes_seq = primes()
+ bg_alphabet_seq = alphabet(code='bg')
+ lat_alphabet_seq = alphabet(code='lat')
+ for elem in generators:
+ if 'letters' in elem:
+ letters_seq = alphabet(letters=elem['letters'])
+ if generator_definitions:
+ keys = generator_definitions.keys()
+ values = generator_definitions.values()
+ additional_generators = dict(zip(keys, values))
+ for elem in generators:
+ if elem['sequence'] == 'fibonacci':
+ sequence = fibonacci_seq
+ elif elem['sequence'] == 'primes':
+ sequence = primes_seq
+ elif elem['sequence'] == 'alphabet' and 'letters' in elem:
+ sequence = letters_seq
+ elif elem['sequence'] == 'alphabet' and elem['code'] == 'bg':
+ sequence = bg_alphabet_seq
+ elif elem['sequence'] == 'alphabet' and elem['code'] == 'lat':
+ sequence = lat_alphabet_seq
+ elif generator_definitions:
+ sequence = additional_generators[elem['sequence']]()
+ while elem['length'] > 0:
+ yield next(sequence)
+ elem['length'] -= 1
for elem in generators
е много лоша идея.
generators
спокойно може да е безкрайна редица и този for никога няма да приключи и да се стигне до yield-ването по-надолу.