-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP4M_Notebook_3
More file actions
5410 lines (5410 loc) · 304 KB
/
P4M_Notebook_3
File metadata and controls
5410 lines (5410 loc) · 304 KB
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
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.7"
},
"colab": {
"provenance": []
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "6wh71ZCco1Nc"
},
"source": [
"# Part 3: Lists\n",
"\n",
"Python provides a powerful set of tools to create and manipulate lists of data. In this part, we take a deep dive into the Python list type. This includes mutability, list methods, and slicing.\n",
"\n",
"\n",
"Then we use Python lists to implement and optimize the Sieve of Eratosthenes, which will produce a list of all prime numbers up to a big number (like 10 million) in a snap. Along the way, we introduce some Python techniques for data analysis and visualization."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "V1d8-qavo1Ng"
},
"source": [
"## Primality testing"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "o8GcrfMBo1Ng"
},
"source": [
"Before diving into lists, we recall the **brute force** primality test that we created in the last lesson. To test whether a number `n` is prime, we can simply check for factors. This yields the following primality test."
]
},
{
"cell_type": "code",
"metadata": {
"id": "PmShUfrWo1Nh"
},
"source": [
"def is_prime(n):\n",
" '''\n",
" Checks whether the argument n is a prime number.\n",
" Uses a brute force search for factors between 1 and n.\n",
" '''\n",
" for j in range(2,n): # the range of numbers 2,3,...,n-1.\n",
" if n%j == 0: # is n divisible by j?\n",
" print(\"{} is a factor of {}.\".format(j,n))\n",
" return False\n",
" return True"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "rluOFbiwty_y",
"outputId": "0669f029-c0fd-400a-a26f-0b6ba1b909ee"
},
"source": [
"is_prime(743)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 25
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ps6dGQ_lo1Nh"
},
"source": [
"We can also implement this test with a **while loop** instead of a for loop. This doesn't make much of a difference, in Python 3.x. (In Python 2.x, this would save memory)."
]
},
{
"cell_type": "code",
"metadata": {
"id": "uyU1DxPjo1Nh"
},
"source": [
"def is_prime(n):\n",
" '''\n",
" Checks whether the argument n is a prime number.\n",
" Uses a brute force search for factors between 1 and n.\n",
" '''\n",
" j = 2\n",
" while j < n: # j will proceed through the list of numbers 2,3,...,n-1.\n",
" if n%j == 0: # is n divisible by j?\n",
" print(\"{} is a factor of {}.\".format(j,n))\n",
" return False\n",
" j = j + 1 # There's a Python abbreviation for this: j += 1.\n",
" return True"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "n8VNDo3Ro1Nh",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "28abf496-99e4-4dfc-82d6-476c680344fc"
},
"source": [
"is_prime(10001)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"73 is a factor of 10001.\n"
],
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {
"tags": []
},
"execution_count": 3
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "EwsTzmDJo1Nh",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d040b48e-3dd3-4a34-c05d-dfb7ca98f06e"
},
"source": [
"is_prime(101)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {
"tags": []
},
"execution_count": 4
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LMiisxZko1Ni"
},
"source": [
"If $n$ is a prime number, then the `is_prime(n)` function will iterate through all the numbers between $2$ and $n-1$. But this is overkill! Indeed, if $n$ is not prime, it will have a factor between $2$ and the square root of $n$. This is because factors come in pairs: if $ab = n$, then one of the factors, $a$ or $b$, must be less than or equal to the square root of $n$. So it suffices to search for factors up to (and including) the square root of $n$."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QlS5mEtko1Ni"
},
"source": [
"Even though we've made our own sqrt function, we load a fast one from the [standard math package](https://docs.python.org/3/library/math.html). You can use this for square roots, trig functions, logs, and more. Click the previous link for documentation. This package doesn't load automatically when you start Python, so you have to load it with a little Python code."
]
},
{
"cell_type": "code",
"metadata": {
"id": "StYgB3R2o1Ni"
},
"source": [
"from math import sqrt"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "g5qCsftto1Ni"
},
"source": [
"This command **imports** the square root function (`sqrt`) from the **package** called `math`. Now you can find square roots."
]
},
{
"cell_type": "code",
"metadata": {
"id": "yky_CASQo1Ni",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "ffc9c2f6-958c-4bc1-b3b7-32135fbcd377"
},
"source": [
"sqrt(1000)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"31.622776601683793"
]
},
"metadata": {
"tags": []
},
"execution_count": 6
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "G6KIJi-Go1Ni"
},
"source": [
"There are a few different ways to import functions from packages. The above syntax is a good starting point, but sometimes problems can arise if different packages have functions with the same name. Here are a few methods of importing the `sqrt` function and how they differ.\n",
"\n",
"`from math import sqrt`: After this command, `sqrt` will refer to the function from the `math` package (overriding any previous definition).\n",
"\n",
"`import math`: After this command, all the functions from the `math` package will be imported. But to call `sqrt`, you would type a command like `math.sqrt(1000)`. This is convenient if there are potential conflicts with other packages.\n",
"\n",
"`from math import *`: After this command, all the functions from the `math` package will be imported. To call them, you can access them directly with a command like `sqrt(1000)`. This can easily cause conflicts with other packages, since packages can have hundreds of functions in them!\n",
"\n",
"`import math as mth`: Some people like abbreviations. This imports all the functions from the `math` package. To call one, you type a command like `mth.sqrt(1000)`."
]
},
{
"cell_type": "code",
"metadata": {
"id": "DkMBWCH2o1Nj"
},
"source": [
"import math"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "JCOkoqBJo1Nj",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "2251dd8d-06a2-4336-d5d8-81e8efc1f7de"
},
"source": [
"math.sqrt(1000)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"31.622776601683793"
]
},
"metadata": {
"tags": []
},
"execution_count": 206
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "1wHHxCBvo1Nj",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 166
},
"outputId": "1e07e4dc-0f4e-412c-8289-bbbd4615876b"
},
"source": [
"factorial(10) # This will cause an error!"
],
"execution_count": null,
"outputs": [
{
"output_type": "error",
"ename": "NameError",
"evalue": "ignored",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-9-e379444d4994>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfactorial\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# This will cause an error!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'factorial' is not defined"
]
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "q3_f65bdo1Nj",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "7815180e-367a-4ff8-e259-b13a0cabe4bc"
},
"source": [
"math.factorial(10) # This is ok, since the math package comes with a function called factorial."
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"3628800"
]
},
"metadata": {
"tags": []
},
"execution_count": 10
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PercB7IRo1Nj"
},
"source": [
"Now let's improve our `is_prime(n)` function by searching for factors only up to the square root of the number `n`. We consider two options."
]
},
{
"cell_type": "code",
"metadata": {
"id": "1jFrsNtvo1Nj"
},
"source": [
"def is_prime_slow(n):\n",
" '''\n",
" Checks whether the argument n is a prime number.\n",
" Uses a brute force search for factors between 1 and n.\n",
" '''\n",
" j = 2\n",
" while j <= sqrt(n): # j will proceed through the list of numbers 2,3,... up to sqrt(n).\n",
" if n%j == 0: # is n divisible by j?\n",
" print(\"{} is a factor of {}.\".format(j,n))\n",
" return False\n",
" j = j + 1 # There's a Python abbreviation for this: j += 1.\n",
" return True"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "kivEWwP8o1Nj"
},
"source": [
"def is_prime_fast(n):\n",
" '''\n",
" Checks whether the argument n is a prime number.\n",
" Uses a brute force search for factors between 1 and n.\n",
" '''\n",
" j = 2\n",
" root_n = sqrt(n)\n",
" while j <= root_n: # j will proceed through the list of numbers 2,3,... up to sqrt(n).\n",
" if n%j == 0: # is n divisible by j?\n",
" print(\"{} is a factor of {}.\".format(j,n))\n",
" return False\n",
" j = j + 1 # There's a Python abbreviation for this: j += 1.\n",
" return True"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "MYRn_kwAo1Nk",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "08be7a11-7e1f-4bf9-e930-1436e1c9f1cf"
},
"source": [
"is_prime_fast(1000003)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {
"tags": []
},
"execution_count": 15
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "CycTNs3Yo1Nk",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "942763ac-9be3-4c3b-fd7d-545b1b5eea42"
},
"source": [
"is_prime_slow(1000003)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {
"tags": []
},
"execution_count": 16
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a2_C-DRco1Nk"
},
"source": [
"I've chosen function names with \"fast\" and \"slow\" in them. But what makes them faster or slower? Are they faster than the original? And how can we tell?\n",
"\n",
"Python comes with a great set of tools for these questions. The simplest (for the user) are the time utilities. By placing the **magic** `%timeit` before a command, Python does something like the following:\n",
"\n",
"1. Python makes a little container in your computer devoted to the computations, to avoid interference from other running programs if possible.\n",
"2. Python executes the command lots and lots of times.\n",
"3. Python averages the amount of time taken for each execution. \n",
"\n",
"Give it a try below, to compare the speed of the functions `is_prime` (the original) with the new `is_prime_fast` and `is_prime_slow`. Note that the `%timeit` commands might take a little while."
]
},
{
"cell_type": "code",
"metadata": {
"id": "9362eqX8o1Nk",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a0edf456-7d33-4036-e467-548eeb6aff0b"
},
"source": [
"%timeit is_prime_fast(1000003)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"The slowest run took 5.21 times longer than the fastest. This could mean that an intermediate result is being cached.\n",
"10000 loops, best of 3: 115 µs per loop\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "GlQqgs6Fo1Nk",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f2a6060b-89f8-4dd6-a793-cd36b793d74f"
},
"source": [
"%timeit is_prime_slow(1000003)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"10000 loops, best of 3: 158 µs per loop\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "MMoNyEsOo1Nk",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "1e55e0e3-12e2-4cea-b4fb-6ef9e6dcaab1"
},
"source": [
"%timeit is_prime(1000003)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"10 loops, best of 3: 103 ms per loop\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uR7IkJbEo1Nk"
},
"source": [
"Time is measured in seconds, milliseconds (1 ms = 1/1000 second), microseconds (1 µs = 1/1,000,000 second), and nanoseconds (1 ns = 1/1,000,000,000 second). So it might appear at first that `is_prime` is the fastest, or about the same speed. But check the units! The other two approaches are about a thousand times faster! How much faster were they on your computer?"
]
},
{
"cell_type": "code",
"metadata": {
"id": "hPOknCuUo1Nk",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "83bf3191-aecc-430a-a20a-f6d0c41f30fe"
},
"source": [
"is_prime_fast(10000000000037) # Don't try this with `is_prime` unless you want to wait for a long time!"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {
"tags": []
},
"execution_count": 21
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YtkronFFo1Nl"
},
"source": [
"Indeed, the `is_prime_fast(n)` function will go through a loop of length about `sqrt(n)` when `n` is prime. But `is_prime(n)` will go through a loop of length about `n`. Since `sqrt(n)` is much less than `n`, especially when `n` is large, the `is_prime_fast(n)` function is much faster.\n",
"\n",
"Between `is_prime_fast` and `is_prime_slow`, the difference is that the `fast` version **precomputes** the square root `sqrt(n)` before going through the loop, where the `slow` version repeats the `sqrt(n)` every time the loop is repeated. Indeed, writing `while j <= sqrt(n):` suggests that Python might execute `sqrt(n)` every time to check. This *might* lead to Python computing the same square root a million times... unnecessarily! \n",
"\n",
"A basic principle of programming is to **avoid repetition**. If you have the memory space, just compute once and store the result. It will probably be faster to pull the result out of memory than to compute it again.\n",
"\n",
"Python does tend to be pretty smart, however. It's possible that Python **is precomputing** `sqrt(n)` even in the slow loop, just because it's clever enough to tell in advance that the same thing is being computed over and over again. This depends on your Python version and takes place behind the scenes. If you want to figure it out, there's a whole set of tools (for advanced programmers) like the [disassembler](https://docs.python.org/3/library/dis.html) to figure out what Python is doing.\n",
"\n",
"If you feel like looking under the hood, the next few lines will display the `is_prime_fast` and `is_prime_slow` functions to bytecode. Can you see how the `sqrt(n)` computation is carried out differently?"
]
},
{
"cell_type": "code",
"metadata": {
"id": "hislzK3Lo1Nl"
},
"source": [
"from dis import dis"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "wQX1FSObo1Nl",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "97fa4d26-8ef5-4d0c-a45c-8af1434ef729"
},
"source": [
"dis(is_prime_fast)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
" 6 0 LOAD_CONST 1 (2)\n",
" 2 STORE_FAST 1 (j)\n",
"\n",
" 7 4 LOAD_GLOBAL 0 (sqrt)\n",
" 6 LOAD_FAST 0 (n)\n",
" 8 CALL_FUNCTION 1\n",
" 10 STORE_FAST 2 (root_n)\n",
"\n",
" 8 12 SETUP_LOOP 52 (to 66)\n",
" >> 14 LOAD_FAST 1 (j)\n",
" 16 LOAD_FAST 2 (root_n)\n",
" 18 COMPARE_OP 1 (<=)\n",
" 20 POP_JUMP_IF_FALSE 64\n",
"\n",
" 9 22 LOAD_FAST 0 (n)\n",
" 24 LOAD_FAST 1 (j)\n",
" 26 BINARY_MODULO\n",
" 28 LOAD_CONST 2 (0)\n",
" 30 COMPARE_OP 2 (==)\n",
" 32 POP_JUMP_IF_FALSE 54\n",
"\n",
" 10 34 LOAD_GLOBAL 1 (print)\n",
" 36 LOAD_CONST 3 ('{} is a factor of {}.')\n",
" 38 LOAD_ATTR 2 (format)\n",
" 40 LOAD_FAST 1 (j)\n",
" 42 LOAD_FAST 0 (n)\n",
" 44 CALL_FUNCTION 2\n",
" 46 CALL_FUNCTION 1\n",
" 48 POP_TOP\n",
"\n",
" 11 50 LOAD_CONST 4 (False)\n",
" 52 RETURN_VALUE\n",
"\n",
" 12 >> 54 LOAD_FAST 1 (j)\n",
" 56 LOAD_CONST 5 (1)\n",
" 58 BINARY_ADD\n",
" 60 STORE_FAST 1 (j)\n",
" 62 JUMP_ABSOLUTE 14\n",
" >> 64 POP_BLOCK\n",
"\n",
" 13 >> 66 LOAD_CONST 6 (True)\n",
" 68 RETURN_VALUE\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "M_T0805ko1Nl",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "10dd49ba-41ee-472e-f572-c5a616b136f4"
},
"source": [
"dis(is_prime_slow)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
" 6 0 LOAD_CONST 1 (2)\n",
" 2 STORE_FAST 1 (j)\n",
"\n",
" 7 4 SETUP_LOOP 56 (to 62)\n",
" >> 6 LOAD_FAST 1 (j)\n",
" 8 LOAD_GLOBAL 0 (sqrt)\n",
" 10 LOAD_FAST 0 (n)\n",
" 12 CALL_FUNCTION 1\n",
" 14 COMPARE_OP 1 (<=)\n",
" 16 POP_JUMP_IF_FALSE 60\n",
"\n",
" 8 18 LOAD_FAST 0 (n)\n",
" 20 LOAD_FAST 1 (j)\n",
" 22 BINARY_MODULO\n",
" 24 LOAD_CONST 2 (0)\n",
" 26 COMPARE_OP 2 (==)\n",
" 28 POP_JUMP_IF_FALSE 50\n",
"\n",
" 9 30 LOAD_GLOBAL 1 (print)\n",
" 32 LOAD_CONST 3 ('{} is a factor of {}.')\n",
" 34 LOAD_ATTR 2 (format)\n",
" 36 LOAD_FAST 1 (j)\n",
" 38 LOAD_FAST 0 (n)\n",
" 40 CALL_FUNCTION 2\n",
" 42 CALL_FUNCTION 1\n",
" 44 POP_TOP\n",
"\n",
" 10 46 LOAD_CONST 4 (False)\n",
" 48 RETURN_VALUE\n",
"\n",
" 11 >> 50 LOAD_FAST 1 (j)\n",
" 52 LOAD_CONST 5 (1)\n",
" 54 BINARY_ADD\n",
" 56 STORE_FAST 1 (j)\n",
" 58 JUMP_ABSOLUTE 6\n",
" >> 60 POP_BLOCK\n",
"\n",
" 12 >> 62 LOAD_CONST 6 (True)\n",
" 64 RETURN_VALUE\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "1mendW3Uo1Nl",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "9f06ccc6-612e-4855-d6ea-5cb221333843"
},
"source": [
"is_prime_fast(10**14 + 37) # This might get a bit of delay."
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"1858741 is a factor of 100000000000037.\n"
],
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {
"tags": []
},
"execution_count": 26
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DUEOKxtoo1Nm"
},
"source": [
"Now we have a function `is_prime_fast(n)` that is speedy for numbers `n` in the trillions! You'll probably start to hit a delay around $10^{15}$ or so, and the delays will become intolerable if you add too many more digits. In a future lesson, we will see a different primality test that will be essentially instant even for numbers around $10^{1000}$! "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NCv3bAIco1Nm"
},
"source": [
"### Exercises\n",
"\n",
"1. To check whether a number `n` is prime, you can first check whether `n` is even, and then check whether `n` has any odd factors. Change the `is_prime_fast` function by implementing this improvement. How much of a speedup did you get?\n",
"\n",
"2. Use the `%timeit` tool to study the speed of `is_prime_fast` for various sizes of `n`. Using about 10 data points, relate the size of `n` to the time taken by the `is_prime_fast` function.\n",
"\n",
"3. Write a function `is_square(n)` to test whether a given integer `n` is a perfect square (like 0, 1, 4, 9, 16, etc.). How fast can you make it run? Describe the different approaches you try and which are fastest."
]
},
{
"cell_type": "code",
"metadata": {
"id": "w4J4ijDBGUrX"
},
"source": [
"#1\n",
"def is_prime_fast(n): # Original is_prime function used to compare my new is_prime function created below.\n",
" '''\n",
" Checks whether the argument n is a prime number.\n",
" Uses a brute force search for factors between 1 and n.\n",
" '''\n",
" j = 2\n",
" root_n = sqrt(n)\n",
" while j <= root_n: # j will proceed through the list of numbers 2,3,... up to sqrt(n).\n",
" if n%j == 0: # is n divisible by j?\n",
" #print(\"{} is a factor of {}.\".format(j,n))\n",
" return False\n",
" j = j + 1 # There's a Python abbreviation for this: j += 1.\n",
" return True"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "GfBu6NqNG3oz",
"outputId": "6e34d0d6-84a3-46d2-e696-a79f85c58af6"
},
"source": [
"%timeit is_prime_fast(1000003)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"10000 loops, best of 3: 117 µs per loop\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "jdqXqY0aI1-f"
},
"source": [
"#1\n",
"def is_prime_even_odd(n): #My new is_prime function which first checks whether n is even, and then checks whether n has any odd factors\n",
" '''\n",
" Checks whether the argument n is a prime number.\n",
" Uses a brute force search for factors between 1 and n.\n",
" '''\n",
" j = 2\n",
" root_n = sqrt(n)\n",
" while j <= root_n: # j will proceed through the list of numbers 2,3,... up to sqrt(n).\n",
" if n%2==0: # is n divisible by 2, an even factor?\n",
" return False\n",
" if n%3 == 0: # is n divisible by 3, an odd factor?\n",
" #print(\"{} is a factor of {}.\".format(j,n))\n",
" return False\n",
" j = j + 1 # There's a Python abbreviation for this: j += 1.\n",
" return True"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "KHIHhiuxNRCC",
"outputId": "1db866f0-c42c-4ac7-8b5b-a8bc57af06d7"
},
"source": [
"is_prime_even_odd(7)"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {
"tags": []
},
"execution_count": 288
}
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "80MZRaMvJgCT",
"outputId": "e7e59d3a-f522-43d3-912f-213541c82643"
},
"source": [
"%timeit is_prime_even_odd(1000003)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"10000 loops, best of 3: 104 µs per loop\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7xFbQ6mqGW-8"
},
"source": [
"The is_prime_fast takes 117 µs per loop. The prime function I created to first check whether n is even, and then check whether n has any odd factors, called is_prime_even_odd takes 104 µs per loop. Therefore, the prime function I created to first check whether n is even, and then check whether n has any odd factors, called is_prime_even_odd, is 1.125 times faster than the function, is_prime_fast.\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "mdtPquZeDaew",
"outputId": "e5b4d636-670e-4e00-cb55-8c524d0018ec"
},
"source": [
"%timeit is_prime_fast(1)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"The slowest run took 33.05 times longer than the fastest. This could mean that an intermediate result is being cached.\n",
"10000000 loops, best of 3: 162 ns per loop\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "fNdjv2-yD2Bh",
"outputId": "4ffc9de9-af66-4db5-ba7f-e55e0c289562"
},
"source": [
"%timeit is_prime_fast(2)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"The slowest run took 23.20 times longer than the fastest. This could mean that an intermediate result is being cached.\n",
"10000000 loops, best of 3: 163 ns per loop\n"
],