Решение на Генератори и итератори от Александър Танков

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

Към профила на Александър Танков

Резултати

  • 8 точки от тестове
  • 0 бонус точки
  • 8 точки общо
  • 11 успешни тест(а)
  • 3 неуспешни тест(а)

Код

from itertools import cycle
from math import factorial
MAX_FUNC_ARG = 3
def fibonacci():
last_value = 1
result = 1
yield last_value
yield result
while True:
yield result + last_value
temp = last_value
last_value = result
result += temp
def primes():
value = 2
while True:
if is_prime(value):
yield value
value += 1
def is_prime(n):
if n < 0:
return False
if n == 1 or n == 0:
return False
for numbers in range(2, n):
if n % numbers == 0:
return False
return True
#TODO: can make this with dict and for value is ord(bg'a') and last char and key is bg
def alphabet(code='', letters=''):
if letters != '':
idx = 0
while idx < len(letters):
yield letters[idx]
idx += 1
elif code == 'lat':
idx = ord('a')
while idx <= ord('z'):
yield chr(idx)
idx += 1
else:
idx = ord('а')
while idx <= ord('я'):
if idx != ord('ы') and idx != ord('э'):
yield chr(idx)
idx += 1
def ones():
while True:
yield 1
def naturals():
number = 1
while True:
yield number
number += 1
def multiples_of(num):
i = 1
while True:
yield num * i
i += 1
def intertwined_sequences(code, generator_definitions=''):
generators = {}
for item in code:
if item['sequence'] not in generators:
possibles = globals().copy()
possibles.update(locals())
if len(item) >= MAX_FUNC_ARG:
args = {}
for key in item:
if key != 'sequence' and key != 'length':
args[key] = item[key]
value = possibles.get(item['sequence'])(**args)
for idx in range(0, item['length']):
yield next(value)
generators[item['sequence']] = value
else:
value = None
if item['sequence'] in generator_definitions:
value = iter(generator_definitions[item['sequence']]())
else:
value = possibles.get(item['sequence'])()
for idx in range(0, item['length']):
yield next(value)
generators[item['sequence']] = value
else:
for idx in range(0, item['length']):
yield next(generators[item['sequence']])
def endless_growing_sequences():
for i, generator_key in enumerate(cycle(['fibonacci', 'primes'])):
yield {'sequence': generator_key, 'length': i + 1}
def square():
n = 1
while True:
yield n * n
n += 1
def square_from_to(from_=5, to_=10):
for n in range(from_, to_ + 1):
yield n * n
def pentagonal():
n = 1
while True:
yield int((3 * n * n - n) / 2)
n += 1
def pentagonal_from_to(from_=5, to_=10):
for n in range(from_, to_ + 1):
yield int((3 * n * n - n) / 2)
def catalan():
n = 0
while True:
yield int(factorial(2 * n) / factorial(n + 1) / factorial(n))
n += 1
def catalan_from_to(from_=5, to_=10):
for n in range(from_, to_ + 1):
yield int(factorial(2 * n) / factorial(n + 1) / factorial(n))

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

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

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

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

----------------------------------------------------------------------
Ran 14 tests in 7.521s

FAILED (errors=3)

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

Александър обнови решението на 03.04.2015 16:00 (преди над 9 години)

+from itertools import cycle
+from math import factorial
+
+
+MAX_FUNC_ARG = 3
+
+
+def fibonacci():
+ last_value = 1
+ result = 1
+ yield last_value
+ yield result
+ while True:
+ yield result + last_value
+ temp = last_value
+ last_value = result
+ result += temp
+
+
+def primes():
+ value = 2
+ while True:
+ if is_prime(value):
+ yield value
+ value += 1
+
+
+def is_prime(n):
+ if n < 0:
+ return False
+ if n == 1 or n == 0:
+ return False
+ for numbers in range(2, n):
+ if n % numbers == 0:
+ return False
+ return True
+
+
+#TODO: can make this with dict and for value is ord(bg'a') and last char and key is bg
+def alphabet(code='', letters=''):
+ if letters != '':
+ idx = 0
+ while idx < len(letters):
+ yield letters[idx]
+ idx += 1
+ elif code == 'lat':
+ idx = ord('a')
+ while idx <= ord('z'):
+ yield chr(idx)
+ idx += 1
+ else:
+ idx = ord('а')
+ while idx <= ord('я'):
+ if idx != ord('ы') and idx != ord('э'):
+ yield chr(idx)
+ idx += 1
+
+
+def ones():
+ while True:
+ yield 1
+
+
+def naturals():
+ number = 1
+ while True:
+ yield number
+ number += 1
+
+
+def multiples_of(num):
+ i = 1
+ while True:
+ yield num * i
+ i += 1
+
+
+def intertwined_sequences(code, generator_definitions=''):
+ generators = {}
+ for item in code:
+ if item['sequence'] not in generators:
+ possibles = globals().copy()
+ possibles.update(locals())
+ if len(item) >= MAX_FUNC_ARG:
+ args = {}
+ for key in item:
+ if key != 'sequence' and key != 'length':
+ args[key] = item[key]
+ value = possibles.get(item['sequence'])(**args)
+ for idx in range(0, item['length']):
+ yield next(value)
+ generators[item['sequence']] = value
+ else:
+ value = None
+ if item['sequence'] in generator_definitions:
+ value = iter(generator_definitions[item['sequence']]())
+ else:
+ value = possibles.get(item['sequence'])()
+
+ for idx in range(0, item['length']):
+ yield next(value)
+ generators[item['sequence']] = value
+ else:
+ for idx in range(0, item['length']):
+ yield next(generators[item['sequence']])
+
+
+def endless_growing_sequences():
+ for i, generator_key in enumerate(cycle(['fibonacci', 'primes'])):
+ yield {'sequence': generator_key, 'length': i + 1}
+
+
+def square():
+ n = 1
+ while True:
+ yield n * n
+ n += 1
+
+
+def square_from_to(from_=5, to_=10):
+ for n in range(from_, to_ + 1):
+ yield n * n
+
+
+def pentagonal():
+ n = 1
+ while True:
+ yield int((3 * n * n - n) / 2)
+ n += 1
+
+
+def pentagonal_from_to(from_=5, to_=10):
+ for n in range(from_, to_ + 1):
+ yield int((3 * n * n - n) / 2)
+
+
+def catalan():
+ n = 0
+ while True:
+ yield int(factorial(2 * n) / factorial(n + 1) / factorial(n))
+ n += 1
+
+
+def catalan_from_to(from_=5, to_=10):
+ for n in range(from_, to_ + 1):
+ yield int(factorial(2 * n) / factorial(n + 1) / factorial(n))