Решение на Генератори и итератори от Марио Даскалов

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

Към профила на Марио Даскалов

Резултати

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

Код

from itertools import count, accumulate, islice
def fibonacci():
current_number, next_number = 1, 1
while True:
yield current_number
current_number, next_number = next_number, current_number + next_number
def is_prime(n):
return not any(divisor for divisor in range(2, n - 1) if n % divisor == 0)
def primes():
next_prime = 2
while True:
yield next_prime
next_prime = next(filter(is_prime, count(next_prime + 1)))
def alphabet(code=None, letters=None):
if letters is None:
letters = {
'bg': 'абвгдежзийклмнопрстуфхцчшщъьюя',
'lat': 'abcdefghijklmnopqrstuvwxyz'
}[code]
return (letter for letter in letters)
def create_generator(generator_descriptor, generator_definitions):
generator = generator_definitions[generator_descriptor['sequence']]
generator_arguments = generator_descriptor.copy()
del generator_arguments['sequence']
del generator_arguments['length']
return iter(generator(**generator_arguments))
def intertwined_sequences(iterable, generator_definitions={}):
generator_definitions.update({
'fibonacci': fibonacci, 'alphabet': alphabet, 'primes': primes
})
generators = {}
for generator_descriptor in iter(iterable):
sequence_name = generator_descriptor['sequence']
if sequence_name not in generators:
generators[sequence_name] = create_generator(generator_descriptor,
generator_definitions)
generator = generators[sequence_name]
for element in islice(generator, 0, generator_descriptor['length']):
yield element

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

..............
----------------------------------------------------------------------
Ran 14 tests in 1.623s

OK

История (2 версии и 5 коментара)

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

+from itertools import count, accumulate, islice
+
+
+def fibonacci():
+ current_number, next_number = 1, 1
+ while True:
+ yield current_number
+ current_number, next_number = next_number, current_number + next_number
+
+
+def is_prime(n):
+ return not any(divisor for divisor in range(2, n - 1) if n % divisor == 0)
+
+
+def primes():
+ next_prime = 2
+ while True:
+ yield next_prime
+ next_prime = next(filter(is_prime, count(next_prime + 1)))
+
+
+def alphabet(code=None, letters=None):
+ if letters is None:
+ letters = {
+ 'bg': 'абвгдежзийклмнопрстуфхцчшщъьюя',
+ 'lat': 'abcdefghijklmnopqrstuvwxyz'
+ }[code]
+ return (letter for letter in letters)
+
+
+def create_generator(generator_descriptor, generator_definitions):
+ generator = generator_definitions[generator_descriptor['sequence']]
+ generator_arguments = generator_descriptor.copy()
+ del generator_arguments['sequence']
+ del generator_arguments['length']
+ return generator(**generator_arguments)
+
+
+def intertwined_sequences(iterable, generator_definitions={}):
+ generator_definitions.update({
+ 'fibonacci': fibonacci, 'alphabet': alphabet, 'primes': primes
+ })
+ generators = {}
+
+ for generator_descriptor in iter(iterable):
+ sequence_name = generator_descriptor['sequence']
+
+ if sequence_name not in generators:
+ generators[sequence_name] = create_generator(generator_descriptor,
+ generator_definitions)
+ generator = generators[sequence_name]
+
+ for element in islice(generator, 0, generator_descriptor['length']):
+ yield element

Функциите, които са стойности в generator_definitions връщат итеруем обект, който може и да не е итератор, но със сигурност можеш да получиш итератор за него. От друга страна всеки итератор винаги е итератор сам на себе си.

Марио обнови решението на 31.03.2015 22:53 (преди над 9 години)

from itertools import count, accumulate, islice
def fibonacci():
current_number, next_number = 1, 1
while True:
yield current_number
current_number, next_number = next_number, current_number + next_number
def is_prime(n):
return not any(divisor for divisor in range(2, n - 1) if n % divisor == 0)
def primes():
next_prime = 2
while True:
yield next_prime
next_prime = next(filter(is_prime, count(next_prime + 1)))
def alphabet(code=None, letters=None):
if letters is None:
letters = {
'bg': 'абвгдежзийклмнопрстуфхцчшщъьюя',
'lat': 'abcdefghijklmnopqrstuvwxyz'
}[code]
return (letter for letter in letters)
def create_generator(generator_descriptor, generator_definitions):
generator = generator_definitions[generator_descriptor['sequence']]
generator_arguments = generator_descriptor.copy()
del generator_arguments['sequence']
del generator_arguments['length']
- return generator(**generator_arguments)
+ return iter(generator(**generator_arguments))
def intertwined_sequences(iterable, generator_definitions={}):
generator_definitions.update({
'fibonacci': fibonacci, 'alphabet': alphabet, 'primes': primes
})
generators = {}
for generator_descriptor in iter(iterable):
sequence_name = generator_descriptor['sequence']
if sequence_name not in generators:
generators[sequence_name] = create_generator(generator_descriptor,
generator_definitions)
generator = generators[sequence_name]
for element in islice(generator, 0, generator_descriptor['length']):
yield element