Решение на Генератори и итератори от Екатерина Горанова

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

Към профила на Екатерина Горанова

Резултати

  • 9 точки от тестове
  • 0 бонус точки
  • 9 точки общо
  • 13 успешни тест(а)
  • 1 неуспешни тест(а)

Код

from math import sqrt
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a + b
def primes():
prime = 2
while True:
if all([prime % p for p in range(2, int(sqrt(prime)) + 1)]):
yield prime
prime += 1
def alphabet(*args, code=None, letters=None):
predefined = {'lat': list('abcdefghijklmnopqrstuvwxyz'),
'bg': list('абвгдежзийклмнопрстуфхцчшщъьюя')}
if letters:
return iter(letters)
return iter(predefined[code])
def intertwined_sequences(sequences, generator_definitions={}):
generators = {'fibonacci': fibonacci,
'primes': primes, 'alphabet': alphabet}
generators.update(generator_definitions)
instances = {}
for dct in sequences:
arguments = dct.copy()
name = arguments.pop('sequence')
length = arguments.pop('length')
if name not in instances:
instances[name] = iter(generators[name](**arguments))
yield from islice(instances[name], length)

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

.......E......
======================================================================
ERROR: test_infinite_intertwined (test.TestIntertwine)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 65, in thread
    raise TimeoutError
TimeoutError

----------------------------------------------------------------------
Ran 14 tests in 2.348s

FAILED (errors=1)

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

Екатерина обнови решението на 30.03.2015 22:04 (преди над 9 години)

+from math import sqrt
+from itertools import islice
+
+
+def fibonacci():
+ a, b = 0, 1
+ while True:
+ yield b
+ a, b = b, a + b
+
+
+def primes():
+ prime = 2
+ while True:
+ if all([prime % p for p in range(2, int(sqrt(prime)) + 1)]):
+ yield prime
+ prime += 1
+
+
+def alphabet(*args, code=None, letters=None):
+ predefined = {'lat': list('abcdefghijklmnopqrstuvwxyz'),
+ 'bg': list('абвгдежзийклмнопрстуфхцчшщъьюя')}
+ if letters:
+ return iter(list(letters))
+ return iter(predefined[code])
+
+
+def intertwined_sequences(sequences, generator_definitions={}):
+ generators = {'fibonacci': fibonacci,
+ 'primes': primes, 'alphabet': alphabet}
+ generators.update(generator_definitions)
+
+ instances = {}
+
+ for dct in sequences:
+ sequence_name = dct.pop('sequence')
+ length = dct.pop('length')
+ if sequence_name not in instances:
+ instances[sequence_name] = generators[sequence_name](**dct)
+ yield from islice(instances[sequence_name], length)
  • letters може да е безкрайно итеруемо. Да го cast-ваш към list е лоша идея.
  • Някои итеруеми обекти не са итератори сами на себе си.
  • Не е добра идея да мутираш подадените ти аргументи, помисли си как да си спестиш pop-ването.

Екатерина обнови решението на 31.03.2015 21:43 (преди над 9 години)

from math import sqrt
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a + b
def primes():
prime = 2
while True:
if all([prime % p for p in range(2, int(sqrt(prime)) + 1)]):
yield prime
prime += 1
def alphabet(*args, code=None, letters=None):
predefined = {'lat': list('abcdefghijklmnopqrstuvwxyz'),
'bg': list('абвгдежзийклмнопрстуфхцчшщъьюя')}
if letters:
- return iter(list(letters))
+ return iter(letters)
return iter(predefined[code])
def intertwined_sequences(sequences, generator_definitions={}):
generators = {'fibonacci': fibonacci,
'primes': primes, 'alphabet': alphabet}
generators.update(generator_definitions)
instances = {}
for dct in sequences:
- sequence_name = dct.pop('sequence')
- length = dct.pop('length')
+ arguments = dct.copy()
+ sequence_name = arguments.pop('sequence')
+ length = arguments.pop('length')
if sequence_name not in instances:
- instances[sequence_name] = generators[sequence_name](**dct)
+ instances[sequence_name] = generators[sequence_name](**arguments)
yield from islice(instances[sequence_name], length)

Екатерина обнови решението на 02.04.2015 19:10 (преди над 9 години)

from math import sqrt
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a + b
def primes():
prime = 2
while True:
if all([prime % p for p in range(2, int(sqrt(prime)) + 1)]):
yield prime
prime += 1
def alphabet(*args, code=None, letters=None):
predefined = {'lat': list('abcdefghijklmnopqrstuvwxyz'),
'bg': list('абвгдежзийклмнопрстуфхцчшщъьюя')}
if letters:
return iter(letters)
return iter(predefined[code])
def intertwined_sequences(sequences, generator_definitions={}):
generators = {'fibonacci': fibonacci,
'primes': primes, 'alphabet': alphabet}
generators.update(generator_definitions)
instances = {}
for dct in sequences:
arguments = dct.copy()
- sequence_name = arguments.pop('sequence')
+ name = arguments.pop('sequence')
length = arguments.pop('length')
- if sequence_name not in instances:
- instances[sequence_name] = generators[sequence_name](**arguments)
+ if name not in instances:
- yield from islice(instances[sequence_name], length)
+ instances[name] = iter(generators[name](**arguments))
+ yield from islice(instances[name], length)