-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnote.py
1278 lines (964 loc) · 24.8 KB
/
note.py
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# False Value in Python: False, 0, '', None (More to come)
# True Value in Python: Anything else
# 三目运算符:>>> x = 0
# >>> abs(1/x if x != 0 else 0)
# Naming Tips
# Names typically don’t matter for correctness but they matter a lot for composition
# Names should convey the meaning or purpose of the values to which they are bound.
# The type of value bound to the name is best documented in a function's docstring.
# Function names typically convey their effect (print), their behavior (triple), or the value returned (abs).
# Repeated compound expressions
# Meaningful parts of complex expressions
# Names can be long if they help document your code
# Names can be short if they represent generic quantities: counts, arbitrary functions, arguments to mathematical operations, etc.
# n, k, i - Usually integers
# x, y, z - Usually real numbers
# f, g, h - Usually functions
"""
week 1:
a = 1
b = 2
b, a = a+b, b
print(a) #2
print(b) #3
# Importing and arithmetic with call expressions
from operator import add, mul
add(1, 2)
mul(4, 6)
mul(add(4, mul(4, 6)), add(3, 5))
add(4, mul(9, mul(add(4, mul(4, 6)), add(3, 5))))
# Objects
# Note: Download from http://composingprograms.com/shakespeare.txt
shakes = open('shakespeare.txt')
text = shakes.read().split()
len(text)
text[:25]
text.count('the')
text.count('thou')
text.count('you')
text.count('forsooth')
text.count(',')
# Sets
words = set(text)
len(words)
max(words)
max(words, key=len)
# Reversals
'draw'[::-1]
{w for w in words if w == w[::-1] and len(w)>4}
{w for w in words if w[::-1] in words and len(w) == 4}
{w for w in words if w[::-1] in words and len(w) > 6}
# Imports
from math import pi
pi * 71 / 223
from math import sin
sin(pi/2)
# Function values
max
max(3, 4)
f = max
f
f(3, 4)
max = 7
f(3, 4)
f(3, max)
f = 2
# f(3, 4)
__builtins__.max
# User-defined functions
from operator import add, mul
def square(x):
return mul(x, x)
square(21)
square(add(2, 5))
square(square(3))
def sum_squares(x, y):
return add(square(x), square(y))
sum_squares(3, 4)
sum_squares(5, 12)
# area function
def area():
return pi * radius * radius
area()
radius = 20
area()
radius = 10
area()
# Name conflicts
def square(square):
return mul(square, square)
square(4)
# Print
-2
print(-2)
'Go Bears'
print('Go Bears')
print(1, 2, 3)
None
print(None)
x = -2
x
x = print(-2)
x
print(print(1), print(2))
# Addition/Multiplication
2 + 3 * 4 + 5
(2 + 3) * (4 + 5)
# Division
618 / 10
618 // 10
618 % 10
from operator import truediv, floordiv, mod
floordiv(618, 10)
truediv(618, 10)
mod(618, 10)
# Approximation
5 / 3
5 // 3
5 % 3
# Multiple return values
def divide_exact(n, d):
return n // d, n % d
quotient, remainder = divide_exact(618, 10)
# Dostrings, doctests, & default arguments
def divide_exact(n, d=10):
Return the quotient and remainder of dividing N by D.
>>> quotient, remainder = divide_exact(618, 10)
>>> quotient
61
>>> remainder
8
return floordiv(n, d), mod(n, d)
# Return
def end(n, d):
Print the final digits of N in reverse order until D is found.
>>> end(34567, 5)
7
6
5
while n > 0:
last, n = n % 10, n // 10
print(last)
if d == last:
return None
def search(f):
#Return the smallest non-negative integer x for which f(x) is a true value.
x = 0
while True:
if f(x):
return x
x += 1
def is_three(x):
Return whether x is three.
>>> search(is_three)
3
return x == 3
def square(x):
return x * x
def positive(x):
A function that is 0 until square(x)-100 is positive.
>>> search(positive)
11
return max(0, square(x) - 100)
def invert(f):
Return a function g(y) that returns x such that f(x) == y.
>>> sqrt = invert(square)
>>> sqrt(16)
4
return lambda y: search(lambda x: f(x) == y)
# Control
def if_(c, t, f):
if c:
t
else:
f
from math import sqrt
def real_sqrt(x):
Return the real part of the square root of x.
>>> real_sqrt(4)
2.0
>>> real_sqrt(-4)
0.0
if x > 0:
return sqrt(x)
else:
return 0.0
if_(x > 0, sqrt(x), 0.0)
# Control Expressions
def has_big_sqrt(x):
#Return whether x has a big square root.
>>> has_big_sqrt(1000)
True
>>> has_big_sqrt(100)
False
>>> has_big_sqrt(0)
False
>>> has_big_sqrt(-1000)
False
return x > 0 and sqrt(x) > 10
def reasonable(n):
Is N small enough that 1/N can be represented?
>>> reasonable(100)
True
>>> reasonable(0)
True
>>> reasonable(-100)
True
>>> reasonable(10 ** 1000)
False
return n == 0 or 1/n != 0.0
from math import pi, sqrt
def area_square(r):
Return the area of a square with side length R.
return r * r
def area_circle(r):
Return the area of a circle with radius R.
return r * r * pi
def area_hexagon(r):
Return the area of a regular hexagon with side length R.
return r * r * 3 * sqrt(3) / 2
def area(r, shape_constant):
Return the area of a shape from length measurement R.
assert r > 0, 'A length must be positive'
return r * r * shape_constant
def area_square(r):
return area(r, 1)
def area_circle(r):
return area(r, pi)
def area_hexagon(r):
return area(r, 3 * sqrt(3) / 2)
# Functions as arguments
def sum_naturals(n):
Sum the first N natural numbers.
>>> sum_naturals(5)
15
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total
def sum_cubes(n):
Sum the first N cubes of natural numbers.
>>> sum_cubes(5)
#225
total, k = 0, 1
while k <= n:
total, k = total + pow(k, 3), k + 1
return total
def identity(k):
return k
def cube(k):
return pow(k, 3)
def summation(n, term):
Sum the first N terms of a sequence.
>>> summation(5, cube)
225
total, k = 0, 1
while k <= n:
total, k = total + term(k), k + 1
return total
from operator import mul
def pi_term(k):
return 8 / mul(k * 4 - 3, k * 4 - 1)
summation(1000000, pi_term)
# Local function definitions; returning functions
def make_adder(n):
Return a function that takes one argument K and returns K + N.
>>> add_three = make_adder(3)
>>> add_three(4)
7
def adder(k):
return k + n
return adder
make_adder(2000)(19)
# Example: Sound
from wave import open
from struct import Struct
from math import floor
frame_rate = 11025
def encode(x):
Encode float x between -1 and 1 as two bytes.
(See https://docs.python.org/3/library/struct.html)
i = int(16384 * x)
return Struct('h').pack(i)
def play(sampler, name='song.wav', seconds=2):
Write the output of a sampler function as a wav file.
(See https://docs.python.org/3/library/wave.html)
out = open(name, 'wb')
out.setnchannels(1)
out.setsampwidth(2)
out.setframerate(frame_rate)
t = 0
while t < seconds * frame_rate:
sample = sampler(t)
out.writeframes(encode(sample))
t = t + 1
out.close()
def tri(frequency, amplitude=0.3):
A continuous triangle wave.
period = frame_rate // frequency
def sampler(t):
saw_wave = t / period - floor(t / period + 0.5)
tri_wave = 2 * abs(2 * saw_wave) - 1
return amplitude * tri_wave
return sampler
c_freq, e_freq, g_freq = 261.63, 329.63, 392.00
play(tri(e_freq))
def note(f, start, end, fade=.01):
Play f for a fixed duration.
def sampler(t):
seconds = t / frame_rate
if seconds < start:
return 0
elif seconds > end:
return 0
elif seconds < start + fade:
return (seconds - start) / fade * f(t)
elif seconds > end - fade:
return (end - seconds) / fade * f(t)
else:
return f(t)
return sampler
play(note(tri(e_freq), 1, 1.5))
def both(f, g):
return lambda t: f(t) + g(t)
c = tri(c_freq)
e = tri(e_freq)
g = tri(g_freq)
low_g = tri(g_freq / 2)
play(both(note(e, 0, 1/8), note(low_g, 1/8, 3/8)))
play(both(note(c, 0, 1), both(note(e, 0, 1), note(g, 0, 1))))
def mario(c, e, g, low_g):
z = 0
song = note(e, z, z + 1/8)
z += 1/8
song = both(song, note(e, z, z + 1/8))
z += 1/4
song = both(song, note(e, z, z + 1/8))
z += 1/4
song = both(song, note(c, z, z + 1/8))
z += 1/8
song = both(song, note(e, z, z + 1/8))
z += 1/4
song = both(song, note(g, z, z + 1/4))
z += 1/2
song = both(song, note(low_g, z, z + 1/4))
return song
def mario_at(octave):
c = tri(octave * c_freq)
e = tri(octave * e_freq)
g = tri(octave * g_freq)
low_g = tri(octave * g_freq / 2)
return mario(c, e, g, low_g)
play(both(mario_at(1), mario_at(1/2)))
# Composition
def compose1(f, g):
Return a function that composes f and g.
f, g -- functions of a single argument
def h(x):
return f(g(x))
return h
def triple(x):
return 3 * x
squiple = compose1(square, triple)
tripare = compose1(triple, square)
squadder = compose1(square, make_adder(2))
# Currying
from operator import add, mul
def curry2(f):
Curry a two-argument function.
>>> m = curry2(add)
>>> add_three = m(3)
>>> add_three(4)
7
>>> m(2)(1)
3
def g(x):
def h(y):
return f(x, y)
return h
return g
week 2:
# Functional arguments
def apply_twice(f, x):
>>> apply_twice(square, 2)
16
>>> from math import sqrt
>>> apply_twice(sqrt, 16)
2.0
return f(f(x))
def square(x):
return x * x
result = apply_twice(square, 2)
# Functional return values
def make_adder(n):
Return a function that takes one argument k and returns k + n.
>>> add_three = make_adder(3)
>>> add_three(4)
7
def adder(k):
return k + n
return adder
# Lexical scope and returning functions
def f(x, y):
return g(x)
def g(a):
return a + y
# This expression causes an error because y is not bound in g.
# f(1, 2)
# Composition
def compose1(f, g):
Return a function that composes f and g.
f, g -- functions of a single argument
def h(x):
return f(g(x))
return h
def triple(x):
return 3 * x
squiple = compose1(square, triple)
tripare = compose1(triple, square)
squadder = compose1(square, make_adder(2))
# Lambda expressions
x = 10
square = x * x
square = lambda x: x * x
square(4)
# Self Reference
def print_all(k):
#Print all arguments of repeated calls.
>>> f = print_all(1)(2)(3)(4)(5)
1
2
3
4
5
print(k)
return print_all
def print_sums(n):
Print all sums of arguments of repeated calls.
>>> f = print_sums(1)(2)(3)(4)(5)
1
3
6
10
15
print(n)
def next_sum(k):
return print_sums(n+k)
return next_sum
def print_sums(n):
#Print all sums of arguments of repeated calls.
>>> f = print_sums(1)(2)(3)(4)(5)
1
3
6
10
15
print(n)
def next_sum(k, j):
return print_sums(n+k+j)
return next_sum
def split(n):
Split a positive integer into all but its last digit and its last digit.
return n // 10, n % 10
def sum_digits(n):
Return the sum of the digits of positive integer n.
>>> sum_digits(9)
9
>>> sum_digits(18117)
18
>>> sum_digits(9437184)
36
>>> sum_digits(11408855402054064613470328848384)
126
if n < 10:
return n
else:
all_but_last, last = split(n)
return sum_digits(all_but_last) + last
# Iteration vs recursion
def fact_iter(n):
total, k = 1, 1
while k <= n:
total, k = total * k, k + 1
return total
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
# Luhn algorithm: mutual recursion
def luhn_sum(n):
Return the digit sum of n computed by the Luhn algorithm.
>>> luhn_sum(2)
2
>>> luhn_sum(12)
4
>>> luhn_sum(42)
10
>>> luhn_sum(138743)
30
>>> luhn_sum(5105105105105100) # example Mastercard
20
>>> luhn_sum(4012888888881881) # example Visa
90
>>> luhn_sum(79927398713) # from Wikipedia
70
if n < 10:
return n
else:
all_but_last, last = split(n)
return luhn_sum_double(all_but_last) + last
def luhn_sum_double(n):
#Return the Luhn sum of n, doubling the last digit.
all_but_last, last = split(n)
luhn_digit = sum_digits(2 * last)
if n < 10:
return luhn_digit
else:
return luhn_sum(all_but_last) + luhn_digit
# Converting iteration to recursion
def sum_digits_iter(n):
#Sum digits iteratively.
>>> sum_digits_iter(11408855402054064613470328848384)
126
digit_sum = 0
while n > 0:
n, last = split(n)
digit_sum = digit_sum + last
return digit_sum
def sum_digits_rec(n, digit_sum):
#Sum digits using recursion, based on iterative version.
>>> sum_digits_rec(11408855402054064613470328848384, 0)
126
if n == 0:
return digit_sum
else:
n, last = split(n)
return sum_digits_rec(n, digit_sum + last)
# Ordering
def cascade(n):
#Print a cascade of prefixes of n.
>>> cascade(1234)
1234
123
12
1
12
123
1234
if n < 10:
print(n)
else:
print(n)
cascade(n//10)
print(n)
def cascade2(n):
#Print a cascade of prefixes of n.
print(n)
if n >= 10:
cascade(n//10)
print(n)
def inverse_cascade(n):
#Print an inverse cascade of prefixes of n.
>>> inverse_cascade(1234)
1
12
123
1234
123
12
1
grow(n)
print(n)
shrink(n)
def f_then_g(f, g, n):
if n:
f(n)
g(n)
grow = lambda n: f_then_g(grow, print, n//10)
shrink = lambda n: f_then_g(print, shrink, n//10)
# Tree recursion
def fib(n):
#Compute the nth Fibonacci number.
>>> fib(8)
21
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-2) + fib(n-1)
#Knapsack
def knap(n, k):
if n == 0:
return k == 0
with_last = knap(n // 10, k - n % 10)
without_last = knap(n // 10, k)
return with_last or without_last
#Count Partitions
def count_partitions(n, m):
#Count the partitions of n using parts up to size m.
>>> count_partitions(6, 4)
9
>>> count_partitions(10, 10)
42
if n == 0:
return 1
elif n < 0:
return 0
elif m == 0:
return 0
else:
with_m = count_partitions(n-m, m)
without_m = count_partitions(n, m-1)
return with_m + without_m
def knap(n, k):
if n == 0:
return k == 0
with_last = knap(n // 10, k - n % 10)
without_last = knap(n // 10, k)
return with_last or without_last
#Binary Print
def all_nums(k):
def h(k, prefix):
if k == 0:
print(prefix)
return
h(k - 1, prefix * 10)
h(k - 1, prefix * 10 + 1)
h(k, 0)
week 3:
# Lists
odds = [41, 43, 47, 49]
len(odds)
odds[1]
odds[0] - odds[3] + len(odds)
odds[odds[3]-odds[2]]
# Containers
digits = [1, 8, 2, 8]
1 in digits
'1' in digits
[1, 8] in digits
[1, 2] in [[1, 2], 3]
# For statements
def count_while(s, value):
#Count the number of occurrences of value in sequence s.
>>> count_while(digits, 8)
2
total, index = 0, 0
while index < len(s):
if s[index] == value:
total = total + 1
index = index + 1
return total
def count_for(s, value):
#Count the number of occurrences of value in sequence s.
>>> count_for(digits, 8)
2
total = 0
for elem in s:
if elem == value:
total = total + 1
return total
def count_same(pairs):
#Return how many pairs have the same element repeated.
>>> pairs = [[1, 2], [2, 2], [2, 3], [4, 4]]
>>> count_same(pairs)
2
same_count = 0
for x, y in pairs:
if x == y:
same_count = same_count + 1
return same_count
# Ranges
list(range(5, 8)) # >>>[5, 6, 7]
list(range(4)) # >>>[0, 1, 2, 3]
len(range(4)) # >>>4
def sum_below(n):
total = 0
for i in range(n):
total += i
return total
def cheer():
for _ in range(3):
print('Go Bears!')
>>>Go Bears!
>>>Go Bears!
>>>Go Bears!
>>>None
# List comprehensions
odds = [1, 3, 5, 7, 9]
[x+1 for x in odds]
[x for x in odds if 25 % x == 0]
#"Unpacking" a list
a = [1, 2, 3, 4]
b, c, d, e = a
print(b)
from operator import getitem
>>> getitem(pair, 0)
1
>>> getitem(pair, 1)
2
def divisors(n):
#Return the integers that evenly divide n.
>>> divisors(1)
[1]
>>> divisors(4)
[1, 2]
>>> divisors(12)
[1, 2, 3, 4, 6]
>>> [n for n in range(1, 1000) if sum(divisors(n)) == n]
[1, 6, 28, 496]
return [1] + [x for x in range(2, n) if n % x == 0]
>>> print([1,2,3] + sum([[4,5,6]],[]))
[1, 2, 3, 4, 5, 6]
# Rational arithmetic
def add_rational(x, y):
#The sum of rational numbers X and Y.
nx, dx = numer(x), denom(x)
ny, dy = numer(y), denom(y)
return rational(nx * dy + ny * dx, dx * dy)
def mul_rational(x, y):
#The product of rational numbers X and Y.
return rational(numer(x) * numer(y), denom(x) * denom(y))
def rationals_are_equal(x, y):
#True iff rational numbers X and Y are equal.
return numer(x) * denom(y) == numer(y) * denom(x)
def print_rational(x):
#Print rational X.
print(numer(x), "/", denom(x))
# Constructor and selectors
def rational(n, d):
#A representation of the rational number N/D.
return [n, d]
def numer(x):
#Return the numerator of rational number X.
return x[0]
def denom(x):
#Return the denominator of rational number X.
return x[1]
# Improved specification
from fractions import gcd
def rational(n, d):
#A representation of the rational number N/D.
g = gcd(n, d)
return [n//g, d//g]
def numer(x):
#Return the numerator of rational number X in lowest terms and having
the sign of X.
return x[0]
def denom(x):
#Return the denominator of rational number X in lowest terms and positive.
return x[1]
# Functional implementation