Решение на Генератори от Тодор Ганчев

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

Към профила на Тодор Ганчев

Резултати

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

Код

def naturals():
current = 2
while(True):
current += 1
yield current
def primes():
primes = [2]
yield 2
for number in naturals():
is_prime = True
for prime in primes:
if number % prime == 0:
is_prime = False
if is_prime:
primes.append(number)
yield number
def semiprimes():
prime_generator = primes()
primes_list = [next(prime_generator)]
for number in naturals():
if number > primes_list[-1]:
append_more_primes(primes_list, prime_generator, number)
for prime in primes_list:
if number % prime ==0 and number != prime and number / prime in primes_list:
yield number
break
def append_more_primes(primes_list, prime_generator, limit):
while(primes_list[-1] < limit):
primes_list.append(next(prime_generator))

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

....
----------------------------------------------------------------------
Ran 4 tests in 0.019s

OK

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

Тодор обнови решението на 03.05.2012 18:36 (преди над 8 години)

+def naturals():
+ current = 2
+ while(True):
+ current += 1
+ yield current
+
+def primes():
+ primes = [2]
+ yield 2
+
+ for number in naturals():
+ is_prime = True
+ for prime in primes:
+ if number % prime == 0:
+ is_prime = False
+ if is_prime:
+ primes.append(number)
+ yield number
+
+def semiprimes():
+ prime_generator = primes()
+ primes_list = [next(prime_generator)]
+
+ for number in naturals():
+ if number > primes_list[-1]:
+ append_more_primes(primes_list, prime_generator, number)
+ for prime in primes_list:
+ if number % prime ==0 and number != prime and number / prime in primes_list:
+ yield number
+ break
+
+def append_more_primes(primes_list, prime_generator, limit):
+ while(primes_list[-1] < limit):
+ primes_list.append(next(prime_generator))