In [2]:
from math import sqrt

def firstSquareGreaterThan(x: int) -> int:
    r = x + 1
    while True:
        sr = sqrt(r)
        if int(sr) == sr:
            return r
        r = r + 1
In [4]:
def firstSquareGreaterThan(x: int) -> int:
    """
    Returns the first square number greater than x.
    """
    r = x + 1
    while int(sqrt(r)) != sqrt(r):
        r = r + 1
        #break # Not used in this course
    return r

print(firstSquareGreaterThan(1234))
1296
In [8]:
def sqrtButTerrible(n: float) -> float:
    """
    Returns the square root of n (very approximately).
    """
    assert n >= 0, "Imaginary numbers unsupported"
    g = n/2
    while abs(g*g - n) > 0.0001:
        print(g)
        g = (g + n/g) / 2
    return g

print(sqrtButTerrible(9))
4.5
3.25
3.0096153846153846
3.000015360039322
In [10]:
def factorize(n: int) -> None:
    for f in range(1, n):
        if n%f == 0:
            print(f)
            
    print(f)
    
factorize(44100)
1
2
3
4
5
6
7
9
10
12
14
15
18
20
21
25
28
30
35
36
42
45
49
50
60
63
70
75
84
90
98
100
105
126
140
147
150
175
180
196
210
225
245
252
294
300
315
350
420
441
450
490
525
588
630
700
735
882
900
980
1050
1225
1260
1470
1575
1764
2100
2205
2450
2940
3150
3675
4410
4900
6300
7350
8820
11025
14700
22050
44099
In [13]:
for i in range(0, 4, 2):
    print(i)
    
print("-")

for i in range(10, 0, -1):
    print(i)
    
print("-")

for i in range(10, 0, 1):
    print(i)
0
2
-
10
9
8
7
6
5
4
3
2
1
-
In [19]:
def countdown(fr: int, to: int) -> None:
    """
    Counts down from fr to to.
    """
    x = range(fr, to, -1)
    for ct in x:
        ct = ct + 1
        print(ct)
        to = to + 1
    #print(to)
    print("Ignition")
    
countdown(5, 0)
6
5
4
3
2
Ignition
In [24]:
x = print
x("Hello")

q = abs
print(q(-3))
print(abs(-3))
print(q == abs)
w = print
w(q(-42))
Hello
3
3
True
42
In [25]:
#abs = print
#abs(-3)

l = countdown
l(5, 0)
6
5
4
3
2
Ignition
In [27]:
import typing

def primeFactors(n: int, cb: typing.Callable) -> None:
    """
    Call cb(x) for each x where x is a prime factor of n.
    """
    assert n > 0, "Only positive integers have factors"
    least = 2
    while n > 1:
        f = least
        while f < n and n%f != 0:
            f = f + 1
        # print(f)
        cb(f)
        least = f
        n = n // f
        
def printNegative(x: int) -> None:
    print(-x)
        
primeFactors(42, printNegative)
-2
-3
-7