Answers

In [1]:
%pylab inline
Populating the interactive namespace from numpy and matplotlib

3a)

In [2]:
def get_factors(n):
    "Returns all the factors of a number."
    factors = []
    for i in range(1, n+1):
        if n % i == 0:
            factors.append(i)
    return factors

for n in 7, 12:
    print(n, ':', get_factors(n))
7 : [1, 7]
12 : [1, 2, 3, 4, 6, 12]

3b)

In [3]:
def is_prime(n):
    "Tests if a number is prime."
    factors = get_factors(n)
    return len(factors) == 2


for n in 7, 12:
    print(n, ':', is_prime(n))
7 : True
12 : False
In [4]:
# Another version
def is_prime2(n):
    "Tests if a number is prime."
    for i in range(2, n // 2 + 1):
        if n % i == 0:
            return False
    return True

for n in 7, 12:
    print(n, ':', is_prime2(n))
7 : True
12 : False

3c)

In [5]:
for n in range(2, 100):
    if is_prime(n):
        print(n)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
In [6]:
def draw_circle(radius, center_x=0, center_y=0, start_angle=0.0, end_angle=2*pi, npoints=100):
    angles = linspace(start_angle, end_angle, npoints)
    xs = cos(angles) * radius + center_x
    ys = sin(angles) * radius + center_y
    
    plot(xs, ys, 'k-')
    axis('equal')
    axis('off')

draw_circle(2.0)
draw_circle(0.2, -0.8, 0.6)
draw_circle(0.2, 0.8, 0.6)
draw_circle(1.5, 0, 0, pi*5/4, pi*7/4)
savefig('data/smileyface.svg')
In [7]:
def remove_all_2s(lst):
    """Removes all 2s in a list, and returns the list."""
    for n in lst:
        if n == 2:
            lst.remove(n)
    return lst

remove_all_2s([1,2,2,3,2,4,2,5])
Out[7]:
[1, 3, 4, 2, 5]
In [8]: