Primes
Source
HackerEarth: Prime Number
Given an integer n
, display the prime numbers up to n
inclusive.
1
2
>>> list(primes(9))
[2, 3, 5, 7]
My solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from birdseye import eye
from os import system
import doctest
import pytest
import typing
def test_mytest_is_prime_false():
assert not is_prime(-1), 'failed on negative integer value'
assert not is_prime( 0), 'failed on value of zero'
assert not is_prime( 1), 'failed on value of 1'
assert not is_prime( 4), 'failed on value of 4'
def test_mytest_is_prime_true():
assert is_prime(2), 'failed on value of 2'
assert is_prime(3), 'failed on value of 3'
assert is_prime(5), 'failed on value of 5'
@eye
def is_prime(n: int) -> bool:
'''Return True if `n` is prime.
>>> is_prime(2)
True
'''
if n < 2:
return False
for x in range(2, n):
if not n % x:
return False
return True
def test_mytest_primes():
assert tuple(primes(3)) == (2, 3)
assert tuple(primes(7)) == (2, 3, 5, 7)
def test_provided_primes():
assert tuple(primes(9)) == (2, 3, 5, 7)
@eye
def primes(n: int) -> Iterable[int]:
'''Yield prime numbers up to n inclusive.
>>> list(primes(9))
[2, 3, 5, 7]
'''
for x in range(2, n + 1):
if is_prime(x):
yield x
def interactive(solution): # pragma: no cover
while(True):
n = int(input('> '))
for x in solution(n):
print(x, end=' ')
print()
pytest_flags = ['-q', '-x', '--showlocals',
'--cov=./', # pytest-cov
'--cov-branch', # pytest-cov
'--cov-report=term-missing:skip-covered', # pytest-cov
]
def tooling(): # pragma: no cover
system(f'mypy {__file__} --ignore-missing-imports')
system(f'flake8 {__file__}')
doctest.testmod()
pytest_flags.append(__file__)
pytest_ret = pytest.main(pytest_flags)
if pytest_ret == 0:
system('coverage html')
if __name__ == '__main__': # pragma: no cover
from sys import argv
try:
if argv[1] == "-i":
interactive(primes)
except IndexError:
tooling()