Решение на Генератори от Николай Стоицев

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

Към профила на Николай Стоицев

Резултати

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

Код

def primes():
number = 2
while True:
if all([number % divisor for divisor in range(2, number)]):
yield number
number += 1
def semiprimes():
primes_gen = primes()
primes_list = set()
primes_squared_list = set()
number = 4
while True:
next_prime = next(primes_gen)
primes_list.add(next_prime)
primes_squared_list.add(next_prime * next_prime)
factors = prime_factors(number)
if factors.issubset(primes_list) or \
set([number]).issubset(primes_squared_list):
yield number
number += 1
def prime_factors(n):
factors = []
lastresult = n
while 1:
if lastresult == 1:
break
c = 2
while 1:
if lastresult % c == 0:
break
c += 1
if c != n:
factors.append(c)
lastresult /= c
num_factors = len(factors)
if num_factors > 2 or num_factors == 0:
return set([0])
else:
return set(factors)

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

....
----------------------------------------------------------------------
Ran 4 tests in 0.609s

OK

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

Николай обнови решението на 30.04.2012 16:51 (преди над 8 години)

+def primes():
+ number = 2
+ while True:
+ if all([number % divisor for divisor in range(2, number)]):
+ yield number
+ number += 1
+
+
+def semiprimes():
+ primes_gen = primes()
+ primes_list = set()
+ primes_squared_list = set()
+ number = 4
+ while True:
+ next_prime = next(primes_gen)
+ primes_list.add(next_prime)
+ primes_squared_list.add(next_prime * next_prime)
+ factors = prime_factors(number)
+ if factors.issubset(primes_list) or \
+ set([number]).issubset(primes_squared_list):
+ yield number
+ number += 1
+
+
+def prime_factors(n):
+ factors = []
+ lastresult = n
+ while 1:
+ if lastresult == 1:
+ break
+ c = 2
+ while 1:
+ if lastresult % c == 0:
+ break
+ c += 1
+ if c != n:
+ factors.append(c)
+ lastresult /= c
+
+ num_factors = len(factors)
+ if num_factors > 2 or num_factors == 0:
+ return set([0])
+ else:
+ return set(factors)