Решение на Генератори и итератори от Евгени Кунев

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

Към профила на Евгени Кунев

Резултати

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

Код

import math
import string
import itertools
INTERTWINE_SERVICE_KEYS = ['sequence', 'length']
ALPHABETS = {
'lat': string.ascii_lowercase,
'bg': 'абвгдежзийклмнопрстуфхцчшщъьюя',
}
def fibonacci():
a = 0
b = 1
while True:
yield b
b += a
a = b - a
def is_prime(n):
return all(n % i for i in range(2, n))
def primes():
n = 2
while True:
if is_prime(n):
yield n
n += 1
def alphabet(code=None, letters=None):
if code:
yield from iter(ALPHABETS[code])
else:
yield from iter(letters)
BUILTIN_GENERATOR_DEFINITIONS = {
'fibonacci': fibonacci,
'primes': primes,
'alphabet': alphabet,
}
def intertwined_sequences(specfications, generator_definitions=None):
if generator_definitions is None:
generator_definitions = {}
generator_definitions.update(BUILTIN_GENERATOR_DEFINITIONS)
iterators = {}
for spec in specfications:
if spec['sequence'] not in iterators:
generator = generator_definitions[spec['sequence']]
kwargs = {
arg: value
for arg, value in spec.items()
if arg not in INTERTWINE_SERVICE_KEYS
}
iterators[spec['sequence']] = iter(generator(**kwargs))
iterator = iterators[spec['sequence']]
yield from itertools.islice(iterator, spec['length'])

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

..............
----------------------------------------------------------------------
Ran 14 tests in 1.663s

OK

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

Евгени обнови решението на 30.03.2015 19:58 (преди над 9 години)

+import math
+import string
+import itertools
+
+INTERTWINE_SERVICE_KEYS = ['sequence', 'length']
+ALPHABETS = {
+ 'lat': string.ascii_lowercase,
+ 'bg': 'абвгдежзийклмнопрстуфхцчшщъьюя',
+}
+
+
+def fibonacci():
+ a = 0
+ b = 1
+ while True:
+ yield b
+ b += a
+ a = b - a
+
+
+def is_prime(n):
+ return all(n % i for i in range(2, n))
+
+
+def primes():
+ n = 2
+ while True:
+ if is_prime(n):
+ yield n
+ n += 1
+
+
+def alphabet(code=None, letters=None):
+ if code:
+ yield from iter(ALPHABETS[code])
+ else:
+ yield from iter(letters)
+
+
+BUILTIN_GENERATOR_DEFINITIONS = {
+ 'fibonacci': fibonacci,
+ 'primes': primes,
+ 'alphabet': alphabet,
+}
+
+
+def intertwined_sequences(specfications, generator_definitions=None):
+ if generator_definitions is None:
+ generator_definitions = {}
+
+ generator_definitions.update(BUILTIN_GENERATOR_DEFINITIONS)
+ iterators = {}
+
+ for spec in specfications:
+ if spec['sequence'] not in iterators:
+ generator = generator_definitions[spec['sequence']]
+ kwargs = {
+ arg: value
+ for arg, value in spec.items()
+ if arg not in INTERTWINE_SERVICE_KEYS
+ }
+
+ iterators[spec['sequence']] = iter(generator(**kwargs))
+
+ iterator = iterators[spec['sequence']]
+
+ yield from itertools.islice(iterator, spec['length'])