Решение на Генератори и итератори от Димитър Влаховски

Обратно към всички решения

Към профила на Димитър Влаховски

Резултати

  • 10 точки от тестове
  • 0 бонус точки
  • 10 точки общо
  • 14 успешни тест(а)
  • 0 неуспешни тест(а)

Код

import string
def fibonacci():
a = 1
b = 1
while True:
yield a
a, b = b, a+b
def primes():
primes = [2]
yield 2
i = 3
while True:
if all((i % p != 0 for p in primes)):
primes.append(i)
yield i
i += 2
def alphabet(*, code=None, letters=None):
hardcoded = {
'lat': string.ascii_lowercase,
'bg': "абвгдежзийклмнопрстуфхцчшщъьюя",
}
if letters is not None:
return iter(letters)
if code in hardcoded:
return iter(hardcoded[code])
def intertwined_sequences(input_generators, *, generator_definitions={}):
hardcoded = {
'alphabet': alphabet,
'primes': primes,
'fibonacci': fibonacci,
}
generator_definitions.update(hardcoded)
generators = {}
for generator in input_generators:
sequence = generator['sequence']
if sequence not in generators:
args = {key: value for key, value in generator.items()
if key != 'sequence' and key != 'length'}
generators[sequence] = iter(
generator_definitions[sequence](**args))
for i in range(generator['length']):
yield next(generators[sequence])

Лог от изпълнението

..............
----------------------------------------------------------------------
Ran 14 tests in 0.390s

OK

История (1 версия и 0 коментара)

Димитър обнови решението на 03.04.2015 00:08 (преди над 9 години)

+import string
+
+
+def fibonacci():
+ a = 1
+ b = 1
+ while True:
+ yield a
+ a, b = b, a+b
+
+
+def primes():
+ primes = [2]
+ yield 2
+ i = 3
+ while True:
+ if all((i % p != 0 for p in primes)):
+ primes.append(i)
+ yield i
+ i += 2
+
+
+def alphabet(*, code=None, letters=None):
+ hardcoded = {
+ 'lat': string.ascii_lowercase,
+ 'bg': "абвгдежзийклмнопрстуфхцчшщъьюя",
+ }
+
+ if letters is not None:
+ return iter(letters)
+
+ if code in hardcoded:
+ return iter(hardcoded[code])
+
+
+def intertwined_sequences(input_generators, *, generator_definitions={}):
+ hardcoded = {
+ 'alphabet': alphabet,
+ 'primes': primes,
+ 'fibonacci': fibonacci,
+ }
+
+ generator_definitions.update(hardcoded)
+ generators = {}
+
+ for generator in input_generators:
+ sequence = generator['sequence']
+ if sequence not in generators:
+ args = {key: value for key, value in generator.items()
+ if key != 'sequence' and key != 'length'}
+ generators[sequence] = iter(
+ generator_definitions[sequence](**args))
+
+ for i in range(generator['length']):
+ yield next(generators[sequence])