├── LICENSE ├── Lecture Slides ├── 1.1-algo1-intro1.pdf ├── 1.2-algo1-intro2_typed.pdf ├── 1.3-algo1-intro3_typed.pdf ├── 1.4-slides_algo-about_typed.pdf ├── 1.5-slides_algo-merge1_typed.pdf ├── 1.6-slides_algo-merge2_typed.pdf ├── 1.7-slides_algo-merge3_typed.pdf ├── 1.8-slides_algo-guiding_typed.pdf ├── 2.1-algo1-aa-gist_typed.pdf ├── 2.2-slides_algo-asymptotic1_typed.pdf ├── 2.3-slides_algo-asymptotic2_typed.pdf ├── 2.4-slides_algo-asymptotic3_typed.pdf ├── 2.5-slides_algo-asymptotic4_typed.pdf ├── 3.1-slides_algo-inversions1_typed.pdf ├── 3.2-slides_algo-inversions2_typed.pdf ├── 3.3-slides_algo-strassen_typed.pdf ├── 3.4-slides_algo-closest1_typed.pdf ├── 3.5-slides_algo-closest2_typed.pdf ├── 4.1-slides_algo-master1_typed.pdf ├── 4.2-slides_algo-master2_typed.pdf ├── 4.3-slides_algo-master3_typed.pdf ├── 4.4-slides_algo-master4_typed.pdf ├── 4.5-slides_algo-master5_typed.pdf ├── 4.6-slides_algo-master6_typed.pdf ├── 5.1-slides_algo-qsort-intro_typed.pdf ├── 5.2-slides_algo-qsort-partition_typed.pdf ├── 5.3-slides_algo-qsort-correctness_typed.pdf ├── 5.4-slides_algo-qsort-pivot_typed.pdf ├── 6.1-slides_algo-qsort-analysis1_typed.pdf ├── 6.2-slides_algo-qsort-analysis2_typed.pdf ├── 6.3-slides_algo-qsort-analysis3_typed.pdf ├── 7.1-slides_algo-prob_review1_typed.pdf ├── 7.2-slides_algo-prob_review2_typed.pdf ├── 8.1-slides_algo-select-ralgorithm_typed.pdf ├── 8.2-slides_algo-select-ranalysis_typed.pdf ├── 8.3-slides_algo-select-dalgorithm_typed.pdf ├── 8.4-slides_algo-select-danalysis_typed.pdf ├── 8.5-slides_algo-select-danalysis2_typed.pdf ├── 8.6-slides_algo-select-sortinglb_typed.pdf ├── 9.1-slides_algo-karger-overview_typed.pdf ├── 9.2-slides_algo-karger-representations_typed.pdf ├── 9.3-slides_algo-karger-algorithm_typed.pdf ├── 9.4-slides_algo-karger-analysis_typed.pdf ├── 9.5-slides_algo-karger-counting_typed.pdf └── README.md ├── Programming Assignment 1 ├── README.md └── karatsuba.py ├── Programming Assignment 2 ├── IntegerArray.py ├── IntegerArray.txt └── README.md ├── Programming Assignment 3 ├── QuickSort.py ├── QuickSort.txt └── README.md ├── Programming Assignment 4 ├── README.md ├── copy.py ├── copy.pyc ├── kargerMinCut.py ├── kargerMinCut.txt ├── random.py ├── random.pyc └── test.txt └── README.md /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Sheng-Qi Shen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Lecture Slides/1.1-algo1-intro1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.1-algo1-intro1.pdf -------------------------------------------------------------------------------- /Lecture Slides/1.2-algo1-intro2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.2-algo1-intro2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/1.3-algo1-intro3_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.3-algo1-intro3_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/1.4-slides_algo-about_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.4-slides_algo-about_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/1.5-slides_algo-merge1_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.5-slides_algo-merge1_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/1.6-slides_algo-merge2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.6-slides_algo-merge2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/1.7-slides_algo-merge3_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.7-slides_algo-merge3_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/1.8-slides_algo-guiding_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/1.8-slides_algo-guiding_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/2.1-algo1-aa-gist_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/2.1-algo1-aa-gist_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/2.2-slides_algo-asymptotic1_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/2.2-slides_algo-asymptotic1_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/2.3-slides_algo-asymptotic2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/2.3-slides_algo-asymptotic2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/2.4-slides_algo-asymptotic3_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/2.4-slides_algo-asymptotic3_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/2.5-slides_algo-asymptotic4_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/2.5-slides_algo-asymptotic4_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/3.1-slides_algo-inversions1_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/3.1-slides_algo-inversions1_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/3.2-slides_algo-inversions2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/3.2-slides_algo-inversions2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/3.3-slides_algo-strassen_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/3.3-slides_algo-strassen_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/3.4-slides_algo-closest1_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/3.4-slides_algo-closest1_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/3.5-slides_algo-closest2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/3.5-slides_algo-closest2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/4.1-slides_algo-master1_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/4.1-slides_algo-master1_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/4.2-slides_algo-master2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/4.2-slides_algo-master2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/4.3-slides_algo-master3_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/4.3-slides_algo-master3_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/4.4-slides_algo-master4_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/4.4-slides_algo-master4_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/4.5-slides_algo-master5_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/4.5-slides_algo-master5_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/4.6-slides_algo-master6_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/4.6-slides_algo-master6_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/5.1-slides_algo-qsort-intro_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/5.1-slides_algo-qsort-intro_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/5.2-slides_algo-qsort-partition_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/5.2-slides_algo-qsort-partition_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/5.3-slides_algo-qsort-correctness_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/5.3-slides_algo-qsort-correctness_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/5.4-slides_algo-qsort-pivot_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/5.4-slides_algo-qsort-pivot_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/6.1-slides_algo-qsort-analysis1_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/6.1-slides_algo-qsort-analysis1_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/6.2-slides_algo-qsort-analysis2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/6.2-slides_algo-qsort-analysis2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/6.3-slides_algo-qsort-analysis3_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/6.3-slides_algo-qsort-analysis3_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/7.1-slides_algo-prob_review1_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/7.1-slides_algo-prob_review1_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/7.2-slides_algo-prob_review2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/7.2-slides_algo-prob_review2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/8.1-slides_algo-select-ralgorithm_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/8.1-slides_algo-select-ralgorithm_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/8.2-slides_algo-select-ranalysis_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/8.2-slides_algo-select-ranalysis_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/8.3-slides_algo-select-dalgorithm_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/8.3-slides_algo-select-dalgorithm_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/8.4-slides_algo-select-danalysis_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/8.4-slides_algo-select-danalysis_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/8.5-slides_algo-select-danalysis2_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/8.5-slides_algo-select-danalysis2_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/8.6-slides_algo-select-sortinglb_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/8.6-slides_algo-select-sortinglb_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/9.1-slides_algo-karger-overview_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/9.1-slides_algo-karger-overview_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/9.2-slides_algo-karger-representations_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/9.2-slides_algo-karger-representations_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/9.3-slides_algo-karger-algorithm_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/9.3-slides_algo-karger-algorithm_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/9.4-slides_algo-karger-analysis_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/9.4-slides_algo-karger-analysis_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/9.5-slides_algo-karger-counting_typed.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Lecture Slides/9.5-slides_algo-karger-counting_typed.pdf -------------------------------------------------------------------------------- /Lecture Slides/README.md: -------------------------------------------------------------------------------- 1 | Week 1 Lecture slides: 2 | - 1: Divide and Conquer: 3 | - [Integer Multiplication](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/1.2-algo1-intro2_typed.pdf); 4 | - [Karatsuba Multiplication](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/1.3-algo1-intro3_typed.pdf); 5 | - [Merge Sort](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/1.6-slides_algo-merge2_typed.pdf). 6 | - 2: Asymptotic Analysis: 7 | - [Big-oh notation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/2.2-slides_algo-asymptotic1_typed.pdf); 8 | - [Omega and Theta notation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/2.4-slides_algo-asymptotic3_typed.pdf); 9 | 10 | Week 2 Lecture slides: 11 | - 3: Divide and Conquer: 12 | - [Counting Inversions](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/3.2-slides_algo-inversions2_typed.pdf) 13 | - [Matrix Multiplication](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/3.3-slides_algo-strassen_typed.pdf) Strassen’s Algorithm 14 | - [Closest Pair](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/3.4-slides_algo-closest1_typed.pdf) Optional 15 | - 4: The Master Method: 16 | - [Motivation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.1-slides_algo-master1_typed.pdf) 17 | - [Example](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.3-slides_algo-master3_typed.pdf) 18 | - [Proof I](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.4-slides_algo-master4_typed.pdf), [Proof II](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.6-slides_algo-master6_typed.pdf) 19 | 20 | Week 3 Lecture slides: 21 | - 5: Randomized Algorithm - QuickSort: 22 | - [Overview](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.1-slides_algo-qsort-intro_typed.pdf); 23 | - [The Partition Subroutine](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.2-slides_algo-qsort-partition_typed.pdf); 24 | - [Proof](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.3-slides_algo-qsort-correctness_typed.pdf); 25 | - [Choosing a Good Pivot](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.4-slides_algo-qsort-pivot_typed.pdf) 26 | - 6: QuickSort Analysis: 27 | - [the average running time of QuickSort (with random pivots)](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/6.3-slides_algo-qsort-analysis3_typed.pdf) 28 | - 7: Probability Review: 29 | 30 | Week 4 Lecture slides: 31 | - 8: Linear-time Selection 32 | - [Randomized Selection](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/8.1-slides_algo-select-ralgorithm_typed.pdf) 33 | - [Deterministic Selection](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/8.3-slides_algo-select-dalgorithm_typed.pdf) 34 | - 9: Graphs and The Minimum Cut 35 | - [Random Contraction Algorithm](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/9.3-slides_algo-karger-algorithm_typed.pdf) 36 | 37 | -------------------------------------------------------------------------------- /Programming Assignment 1/README.md: -------------------------------------------------------------------------------- 1 | # File Description 2 | - `.py` file is the solution of Week 1 program assignment 3 | - `karatsuba.py` 4 | # Implementation 5 | - [Karatsuba Multiplication](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/1.3-algo1-intro3_typed.pdf) 6 | -------------------------------------------------------------------------------- /Programming Assignment 1/karatsuba.py: -------------------------------------------------------------------------------- 1 | #version 2.7.6 2 | def karatsuba(num1, num2): 3 | num1Str = str(num1) 4 | num2Str = str(num2) 5 | if (num1 < 10) or (num2 < 10): 6 | return num1*num2 7 | 8 | maxLength = max(len(num1Str), len(num2Str)) 9 | splitPosition = maxLength / 2 10 | high1, low1= int(num1Str[:-splitPosition]), int(num1Str[-splitPosition:]) 11 | high2, low2= int(num2Str[:-splitPosition]), int(num2Str[-splitPosition:]) 12 | z0 = karatsuba(low1, low2) 13 | z1 = karatsuba((low1 + high1), (low2 + high2)) 14 | z2 = karatsuba(high1, high2) 15 | 16 | return (z2*10**(2*splitPosition)) + ((z1-z2-z0)*10**(splitPosition))+z0 17 | 18 | 19 | -------------------------------------------------------------------------------- /Programming Assignment 2/IntegerArray.py: -------------------------------------------------------------------------------- 1 | 2 | with open('IntegerArray.txt') as f: 3 | a = [int(x) for x in f] 4 | 5 | def CountSplitInv(B,C): 6 | i = 0 7 | j = 0 8 | count = 0 9 | D = [] 10 | while i 1: 25 | splitposition = n / 2 26 | B,X = Sort_Count(A[:-splitposition]) 27 | C,Y = Sort_Count(A[-splitposition:]) 28 | D,Z = CountSplitInv(B,C) 29 | return D,X+Y+Z 30 | else: 31 | return A,0 32 | 33 | Sort_Count(a) 34 | -------------------------------------------------------------------------------- /Programming Assignment 2/README.md: -------------------------------------------------------------------------------- 1 | # Goal 2 | Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array. 3 | # File Description 4 | - `.txt` files is data file. 5 | - `IntegerArray.txt` consists of 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated.. 6 | - `.py` file is the solution of Week 2 program assignment 7 | - `IntegerArray.py` 8 | # Algorithm 9 | Divide and Conquer: [Counting Inversions](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/3.2-slides_algo-inversions2_typed.pdf) 10 | -------------------------------------------------------------------------------- /Programming Assignment 3/QuickSort.py: -------------------------------------------------------------------------------- 1 | 2 | with open('QuickSort.txt') as f: 3 | a = [int(x) for x in f] 4 | 5 | def FindMedian(A): 6 | minvalue = min(A) 7 | maxvalue = max(A) 8 | for i in range(3): 9 | if A[i] != minvalue and A[i] != maxvalue: 10 | return A[i] 11 | 12 | def ChoosePivot(A,flag): 13 | n = len(A) 14 | first = A[0] 15 | final = A[n-1] 16 | if n/2*2==n: 17 | k = n/2 - 1 18 | middle = A[k] 19 | elif n/2*21: 65 | p = ChoosePivot(A,flag) 66 | A = Swap(A,0,p) 67 | A,pivot_position = Partition(A) 68 | A[:pivot_position],left = QuickSort(A[:pivot_position],flag) 69 | A[pivot_position+1:],right = QuickSort(A[pivot_position+1:],flag) 70 | 71 | return A,left+right+n-1 72 | else: 73 | return A,0 74 | -------------------------------------------------------------------------------- /Programming Assignment 3/README.md: -------------------------------------------------------------------------------- 1 | # Goal 2 | - QuickSort the the array 3 | - compute the total number of comparisions 4 | # File Description 5 | - `.txt` files is data file. 6 | - `QuickSort.txt` consists of 10,000 integers. 7 | - `.py` file is the solution of Week 3 program assignment 8 | - `QuickSort.py` 9 | 10 | # Algorithm 11 | - QuickSort [reference 1](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.1-slides_algo-qsort-intro_typed.pdf), [reference 2](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.2-slides_algo-qsort-partition_typed.pdf). 12 | # Implementation 13 | 1. First pivot 14 | 2. Last pivot 15 | 3. Medium pivot 16 | -------------------------------------------------------------------------------- /Programming Assignment 4/README.md: -------------------------------------------------------------------------------- 1 | # Goal 2 | Compute the minimum cut of graph 3 | # File Description 4 | - `.txt` files is data file. 5 | - `kargerMinCut.txt` consists of 200 vertices. 6 | - `.py` file is the solution of Week 4 program assignment 7 | - `kargerMinCut.py` 8 | # Algorithm 9 | - [Random Contraction Algorithm](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/9.3-slides_algo-karger-algorithm_typed.pdf) 10 | -------------------------------------------------------------------------------- /Programming Assignment 4/copy.py: -------------------------------------------------------------------------------- 1 | """Generic (shallow and deep) copying operations. 2 | 3 | Interface summary: 4 | 5 | import copy 6 | 7 | x = copy.copy(y) # make a shallow copy of y 8 | x = copy.deepcopy(y) # make a deep copy of y 9 | 10 | For module specific errors, copy.Error is raised. 11 | 12 | The difference between shallow and deep copying is only relevant for 13 | compound objects (objects that contain other objects, like lists or 14 | class instances). 15 | 16 | - A shallow copy constructs a new compound object and then (to the 17 | extent possible) inserts *the same objects* into it that the 18 | original contains. 19 | 20 | - A deep copy constructs a new compound object and then, recursively, 21 | inserts *copies* into it of the objects found in the original. 22 | 23 | Two problems often exist with deep copy operations that don't exist 24 | with shallow copy operations: 25 | 26 | a) recursive objects (compound objects that, directly or indirectly, 27 | contain a reference to themselves) may cause a recursive loop 28 | 29 | b) because deep copy copies *everything* it may copy too much, e.g. 30 | administrative data structures that should be shared even between 31 | copies 32 | 33 | Python's deep copy operation avoids these problems by: 34 | 35 | a) keeping a table of objects already copied during the current 36 | copying pass 37 | 38 | b) letting user-defined classes override the copying operation or the 39 | set of components copied 40 | 41 | This version does not copy types like module, class, function, method, 42 | nor stack trace, stack frame, nor file, socket, window, nor array, nor 43 | any similar types. 44 | 45 | Classes can use the same interfaces to control copying that they use 46 | to control pickling: they can define methods called __getinitargs__(), 47 | __getstate__() and __setstate__(). See the documentation for module 48 | "pickle" for information on these methods. 49 | """ 50 | 51 | import types 52 | from copy_reg import dispatch_table 53 | 54 | class Error(Exception): 55 | pass 56 | error = Error # backward compatibility 57 | 58 | try: 59 | from org.python.core import PyStringMap 60 | except ImportError: 61 | PyStringMap = None 62 | 63 | __all__ = ["Error", "copy", "deepcopy"] 64 | 65 | def copy(x): 66 | """Shallow copy operation on arbitrary Python objects. 67 | 68 | See the module's __doc__ string for more info. 69 | """ 70 | 71 | cls = type(x) 72 | 73 | copier = _copy_dispatch.get(cls) 74 | if copier: 75 | return copier(x) 76 | 77 | copier = getattr(cls, "__copy__", None) 78 | if copier: 79 | return copier(x) 80 | 81 | reductor = dispatch_table.get(cls) 82 | if reductor: 83 | rv = reductor(x) 84 | else: 85 | reductor = getattr(x, "__reduce_ex__", None) 86 | if reductor: 87 | rv = reductor(2) 88 | else: 89 | reductor = getattr(x, "__reduce__", None) 90 | if reductor: 91 | rv = reductor() 92 | else: 93 | raise Error("un(shallow)copyable object of type %s" % cls) 94 | 95 | return _reconstruct(x, rv, 0) 96 | 97 | 98 | _copy_dispatch = d = {} 99 | 100 | def _copy_immutable(x): 101 | return x 102 | for t in (type(None), int, long, float, bool, str, tuple, 103 | frozenset, type, xrange, types.ClassType, 104 | types.BuiltinFunctionType, 105 | types.FunctionType): 106 | d[t] = _copy_immutable 107 | for name in ("ComplexType", "UnicodeType", "CodeType"): 108 | t = getattr(types, name, None) 109 | if t is not None: 110 | d[t] = _copy_immutable 111 | 112 | def _copy_with_constructor(x): 113 | return type(x)(x) 114 | for t in (list, dict, set): 115 | d[t] = _copy_with_constructor 116 | 117 | def _copy_with_copy_method(x): 118 | return x.copy() 119 | if PyStringMap is not None: 120 | d[PyStringMap] = _copy_with_copy_method 121 | 122 | def _copy_inst(x): 123 | if hasattr(x, '__copy__'): 124 | return x.__copy__() 125 | if hasattr(x, '__getinitargs__'): 126 | args = x.__getinitargs__() 127 | y = x.__class__(*args) 128 | else: 129 | y = _EmptyClass() 130 | y.__class__ = x.__class__ 131 | if hasattr(x, '__getstate__'): 132 | state = x.__getstate__() 133 | else: 134 | state = x.__dict__ 135 | if hasattr(y, '__setstate__'): 136 | y.__setstate__(state) 137 | else: 138 | y.__dict__.update(state) 139 | return y 140 | d[types.InstanceType] = _copy_inst 141 | 142 | del d 143 | 144 | def deepcopy(x, memo=None, _nil=[]): 145 | """Deep copy operation on arbitrary Python objects. 146 | 147 | See the module's __doc__ string for more info. 148 | """ 149 | 150 | if memo is None: 151 | memo = {} 152 | 153 | d = id(x) 154 | y = memo.get(d, _nil) 155 | if y is not _nil: 156 | return y 157 | 158 | cls = type(x) 159 | 160 | copier = _deepcopy_dispatch.get(cls) 161 | if copier: 162 | y = copier(x, memo) 163 | else: 164 | try: 165 | issc = issubclass(cls, type) 166 | except TypeError: # cls is not a class (old Boost; see SF #502085) 167 | issc = 0 168 | if issc: 169 | y = _deepcopy_atomic(x, memo) 170 | else: 171 | copier = getattr(x, "__deepcopy__", None) 172 | if copier: 173 | y = copier(memo) 174 | else: 175 | reductor = dispatch_table.get(cls) 176 | if reductor: 177 | rv = reductor(x) 178 | else: 179 | reductor = getattr(x, "__reduce_ex__", None) 180 | if reductor: 181 | rv = reductor(2) 182 | else: 183 | reductor = getattr(x, "__reduce__", None) 184 | if reductor: 185 | rv = reductor() 186 | else: 187 | raise Error( 188 | "un(deep)copyable object of type %s" % cls) 189 | y = _reconstruct(x, rv, 1, memo) 190 | 191 | memo[d] = y 192 | _keep_alive(x, memo) # Make sure x lives at least as long as d 193 | return y 194 | 195 | _deepcopy_dispatch = d = {} 196 | 197 | def _deepcopy_atomic(x, memo): 198 | return x 199 | d[type(None)] = _deepcopy_atomic 200 | d[int] = _deepcopy_atomic 201 | d[long] = _deepcopy_atomic 202 | d[float] = _deepcopy_atomic 203 | d[bool] = _deepcopy_atomic 204 | try: 205 | d[complex] = _deepcopy_atomic 206 | except NameError: 207 | pass 208 | d[str] = _deepcopy_atomic 209 | try: 210 | d[unicode] = _deepcopy_atomic 211 | except NameError: 212 | pass 213 | try: 214 | d[types.CodeType] = _deepcopy_atomic 215 | except AttributeError: 216 | pass 217 | d[type] = _deepcopy_atomic 218 | d[xrange] = _deepcopy_atomic 219 | d[types.ClassType] = _deepcopy_atomic 220 | d[types.BuiltinFunctionType] = _deepcopy_atomic 221 | d[types.FunctionType] = _deepcopy_atomic 222 | 223 | def _deepcopy_list(x, memo): 224 | y = [] 225 | memo[id(x)] = y 226 | for a in x: 227 | y.append(deepcopy(a, memo)) 228 | return y 229 | d[list] = _deepcopy_list 230 | 231 | def _deepcopy_tuple(x, memo): 232 | y = [] 233 | for a in x: 234 | y.append(deepcopy(a, memo)) 235 | d = id(x) 236 | try: 237 | return memo[d] 238 | except KeyError: 239 | pass 240 | for i in range(len(x)): 241 | if x[i] is not y[i]: 242 | y = tuple(y) 243 | break 244 | else: 245 | y = x 246 | memo[d] = y 247 | return y 248 | d[tuple] = _deepcopy_tuple 249 | 250 | def _deepcopy_dict(x, memo): 251 | y = {} 252 | memo[id(x)] = y 253 | for key, value in x.iteritems(): 254 | y[deepcopy(key, memo)] = deepcopy(value, memo) 255 | return y 256 | d[dict] = _deepcopy_dict 257 | if PyStringMap is not None: 258 | d[PyStringMap] = _deepcopy_dict 259 | 260 | def _keep_alive(x, memo): 261 | """Keeps a reference to the object x in the memo. 262 | 263 | Because we remember objects by their id, we have 264 | to assure that possibly temporary objects are kept 265 | alive by referencing them. 266 | We store a reference at the id of the memo, which should 267 | normally not be used unless someone tries to deepcopy 268 | the memo itself... 269 | """ 270 | try: 271 | memo[id(memo)].append(x) 272 | except KeyError: 273 | # aha, this is the first one :-) 274 | memo[id(memo)]=[x] 275 | 276 | def _deepcopy_inst(x, memo): 277 | if hasattr(x, '__deepcopy__'): 278 | return x.__deepcopy__(memo) 279 | if hasattr(x, '__getinitargs__'): 280 | args = x.__getinitargs__() 281 | args = deepcopy(args, memo) 282 | y = x.__class__(*args) 283 | else: 284 | y = _EmptyClass() 285 | y.__class__ = x.__class__ 286 | memo[id(x)] = y 287 | if hasattr(x, '__getstate__'): 288 | state = x.__getstate__() 289 | else: 290 | state = x.__dict__ 291 | state = deepcopy(state, memo) 292 | if hasattr(y, '__setstate__'): 293 | y.__setstate__(state) 294 | else: 295 | y.__dict__.update(state) 296 | return y 297 | d[types.InstanceType] = _deepcopy_inst 298 | 299 | def _reconstruct(x, info, deep, memo=None): 300 | if isinstance(info, str): 301 | return x 302 | assert isinstance(info, tuple) 303 | if memo is None: 304 | memo = {} 305 | n = len(info) 306 | assert n in (2, 3, 4, 5) 307 | callable, args = info[:2] 308 | if n > 2: 309 | state = info[2] 310 | else: 311 | state = {} 312 | if n > 3: 313 | listiter = info[3] 314 | else: 315 | listiter = None 316 | if n > 4: 317 | dictiter = info[4] 318 | else: 319 | dictiter = None 320 | if deep: 321 | args = deepcopy(args, memo) 322 | y = callable(*args) 323 | memo[id(x)] = y 324 | if listiter is not None: 325 | for item in listiter: 326 | if deep: 327 | item = deepcopy(item, memo) 328 | y.append(item) 329 | if dictiter is not None: 330 | for key, value in dictiter: 331 | if deep: 332 | key = deepcopy(key, memo) 333 | value = deepcopy(value, memo) 334 | y[key] = value 335 | if state: 336 | if deep: 337 | state = deepcopy(state, memo) 338 | if hasattr(y, '__setstate__'): 339 | y.__setstate__(state) 340 | else: 341 | if isinstance(state, tuple) and len(state) == 2: 342 | state, slotstate = state 343 | else: 344 | slotstate = None 345 | if state is not None: 346 | y.__dict__.update(state) 347 | if slotstate is not None: 348 | for key, value in slotstate.iteritems(): 349 | setattr(y, key, value) 350 | return y 351 | 352 | del d 353 | 354 | del types 355 | 356 | # Helper for instance creation without calling __init__ 357 | class _EmptyClass: 358 | pass 359 | 360 | def _test(): 361 | l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'], 362 | {'abc': 'ABC'}, (), [], {}] 363 | l1 = copy(l) 364 | print l1==l 365 | l1 = map(copy, l) 366 | print l1==l 367 | l1 = deepcopy(l) 368 | print l1==l 369 | class C: 370 | def __init__(self, arg=None): 371 | self.a = 1 372 | self.arg = arg 373 | if __name__ == '__main__': 374 | import sys 375 | file = sys.argv[0] 376 | else: 377 | file = __file__ 378 | self.fp = open(file) 379 | self.fp.close() 380 | def __getstate__(self): 381 | return {'a': self.a, 'arg': self.arg} 382 | def __setstate__(self, state): 383 | for key, value in state.iteritems(): 384 | setattr(self, key, value) 385 | def __deepcopy__(self, memo=None): 386 | new = self.__class__(deepcopy(self.arg, memo)) 387 | new.a = self.a 388 | return new 389 | c = C('argument sketch') 390 | l.append(c) 391 | l2 = copy(l) 392 | print l == l2 393 | print l 394 | print l2 395 | l2 = deepcopy(l) 396 | print l == l2 397 | print l 398 | print l2 399 | l.append({l[1]: l, 'xyz': l[2]}) 400 | l3 = copy(l) 401 | import repr 402 | print map(repr.repr, l) 403 | print map(repr.repr, l1) 404 | print map(repr.repr, l2) 405 | print map(repr.repr, l3) 406 | l3 = deepcopy(l) 407 | import repr 408 | print map(repr.repr, l) 409 | print map(repr.repr, l1) 410 | print map(repr.repr, l2) 411 | print map(repr.repr, l3) 412 | 413 | if __name__ == '__main__': 414 | _test() 415 | -------------------------------------------------------------------------------- /Programming Assignment 4/copy.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Programming Assignment 4/copy.pyc -------------------------------------------------------------------------------- /Programming Assignment 4/kargerMinCut.py: -------------------------------------------------------------------------------- 1 | import random 2 | import copy 3 | 4 | with open('kargerMinCut.txt') as f: 5 | #kargerMinCut 6 | #a = [[int(x) for x in ln.split()] for ln in f] 7 | data_set = [] 8 | for ln in f: 9 | line = ln.split() 10 | if line: 11 | a = [int(x) for x in line] 12 | data_set.append(a) 13 | 14 | def choose_random_edge(data): 15 | a = random.randint(0,len(data)-1) 16 | b = random.randint(1,len(data[a])-1) 17 | return a,b 18 | 19 | def compute_nodes(data): 20 | data_head = [] 21 | for i in xrange(len(data)): 22 | data_head.append(data[i][0]) 23 | return data_head 24 | 25 | def find_index(data_head,data,u,v): 26 | index = data_head.index(data[u][v]) 27 | return index 28 | 29 | def replace(data_head,data,index,u): 30 | for i in data[index][1:]: 31 | index_index = data_head.index(i) 32 | for position,value in enumerate(data[index_index]): 33 | if value == data[index][0]: 34 | data[index_index][position] = data[u][0] 35 | return data 36 | 37 | def merge(data): 38 | u,v = choose_random_edge(data) 39 | #print u,v 40 | data_head = compute_nodes(data) 41 | index = find_index(data_head,data,u,v) 42 | data[u].extend(data[index][1:]) 43 | #print data 44 | data = replace(data_head,data,index,u) 45 | #print data 46 | data[u][1:] = [x for x in data[u][1:] if x!=data[u][0]] 47 | #print data 48 | data.remove(data[index]) 49 | #print data 50 | return data 51 | 52 | def KargerMinCut(data): 53 | 54 | data = copy.deepcopy(data) 55 | while len(data) >2: 56 | data = merge(data) 57 | #print data 58 | num = len(data[0][1:]) 59 | return num 60 | 61 | #KargerMinCut(data_set) 62 | def calc_number(data,iteration): 63 | list = [] 64 | for i in xrange(iteration): 65 | list.append(KargerMinCut(data)) 66 | return min(list) 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /Programming Assignment 4/kargerMinCut.txt: -------------------------------------------------------------------------------- 1 | 1 37 79 164 155 32 87 39 113 15 18 78 175 140 200 4 160 97 191 100 91 20 69 198 196 2 | 2 123 134 10 141 13 12 43 47 3 177 101 179 77 182 117 116 36 103 51 154 162 128 30 3 | 3 48 123 134 109 41 17 159 49 136 16 130 141 29 176 2 190 66 153 157 70 114 65 173 104 194 54 4 | 4 91 171 118 125 158 76 107 18 73 140 42 193 127 100 84 121 60 81 99 80 150 55 1 35 23 93 5 | 5 193 156 102 118 175 39 124 119 19 99 160 75 20 112 37 23 145 135 146 73 35 6 | 6 155 56 52 120 131 160 124 119 14 196 144 25 75 76 166 35 87 26 20 32 23 7 | 7 156 185 178 79 27 52 144 107 78 22 71 26 31 15 56 76 112 39 8 113 93 8 | 8 185 155 171 178 108 64 164 53 140 25 100 133 9 52 191 46 20 150 144 39 62 131 42 119 127 31 7 9 | 9 91 155 8 160 107 132 195 26 20 133 39 76 100 78 122 127 38 156 191 196 115 10 | 10 190 184 154 49 2 182 173 170 161 47 189 101 153 50 30 109 177 148 179 16 163 116 13 90 185 11 | 11 123 134 163 41 12 28 130 13 101 83 77 109 114 21 82 88 74 24 94 48 33 12 | 12 161 109 169 21 24 36 65 50 2 101 159 148 54 192 88 47 11 142 43 70 182 177 179 189 194 33 13 | 13 161 141 157 44 83 90 181 41 2 176 10 29 116 134 182 170 165 173 190 159 47 82 111 142 72 154 110 21 103 130 11 33 138 152 14 | 14 91 156 58 122 62 113 107 73 137 25 19 40 6 139 150 46 37 76 39 127 15 | 15 149 58 68 52 39 67 121 191 1 45 100 18 118 174 40 85 196 122 42 193 119 139 26 127 145 135 57 38 7 16 | 16 48 10 36 187 43 3 114 173 111 142 129 88 189 117 128 147 141 194 180 106 167 179 66 74 136 51 59 17 | 17 48 123 134 36 163 3 44 117 167 161 152 95 170 83 180 77 65 72 109 47 43 88 159 197 28 194 181 49 18 | 18 193 149 56 62 15 160 67 191 140 52 178 96 107 132 1 145 89 198 4 26 73 151 126 34 115 19 | 19 156 80 178 164 108 84 71 174 40 62 113 22 89 45 91 126 195 144 5 14 172 20 | 20 185 122 171 56 8 52 73 191 67 126 9 119 1 89 79 107 96 31 75 55 5 6 34 23 21 | 21 188 187 12 173 180 197 138 167 63 111 95 13 192 116 94 114 105 49 177 51 130 90 11 50 66 157 176 22 | 22 156 27 32 131 7 56 53 81 149 23 100 146 115 26 175 121 96 75 57 39 119 71 132 19 150 140 93 23 | 23 91 122 124 22 200 195 145 5 69 125 55 68 156 20 58 191 4 57 149 6 24 | 24 123 134 161 163 169 72 116 167 30 33 77 162 143 159 187 63 184 130 28 50 153 12 148 11 53 25 | 25 193 185 79 108 8 158 87 73 81 115 39 64 178 132 27 68 127 84 14 52 200 97 6 93 26 | 26 193 58 27 108 52 144 160 18 84 81 22 75 139 166 15 107 198 131 7 9 133 6 27 | 27 156 139 144 166 112 100 26 174 31 42 75 158 122 81 22 7 58 73 89 115 39 25 200 69 169 28 | 28 134 188 24 184 159 29 72 114 152 116 169 173 141 17 111 61 192 90 11 177 179 77 33 66 83 136 29 | 29 48 134 188 13 47 88 3 82 92 28 194 50 192 189 123 199 177 147 43 106 148 197 77 103 129 181 30 | 30 165 123 10 24 41 187 47 168 92 148 197 101 50 2 179 111 130 77 153 199 70 31 | 31 27 171 56 131 146 139 191 89 20 108 38 71 75 69 196 149 97 8 86 98 7 32 | 32 156 149 171 62 22 185 35 124 56 38 158 97 53 121 160 1 191 58 89 127 87 120 39 99 84 60 151 174 6 33 | 33 48 161 109 141 24 187 47 88 168 183 110 103 95 116 28 12 11 13 83 134 63 34 | 34 37 122 171 118 76 131 166 137 40 46 97 87 80 164 127 18 62 52 20 139 35 | 35 79 164 125 32 107 137 75 121 85 55 69 45 193 132 4 5 200 135 76 139 198 6 36 | 36 165 188 17 106 88 16 177 110 147 154 159 179 136 41 50 141 66 162 152 168 184 12 43 72 180 190 77 2 170 61 122 37 | 37 193 149 39 121 191 115 146 52 127 79 198 58 125 38 34 1 76 89 164 97 86 178 108 87 84 124 98 174 195 14 5 57 196 186 38 | 38 193 37 86 32 76 107 73 85 127 100 46 89 31 57 96 158 99 160 45 15 9 39 | 39 193 37 122 102 8 158 32 87 85 81 200 60 5 27 155 1 58 150 15 113 76 84 22 25 151 139 100 14 145 9 7 40 | 40 91 156 122 79 118 125 52 175 87 15 81 166 132 121 19 14 160 34 78 71 41 | 41 36 169 184 116 163 106 189 11 104 61 30 123 129 111 3 47 49 154 161 152 13 153 65 92 183 177 162 95 54 70 108 42 | 42 178 79 27 53 171 164 102 52 87 113 15 191 131 91 62 193 8 122 89 56 4 127 145 112 43 | 43 165 161 12 70 199 54 17 190 16 153 141 36 47 44 194 110 82 189 2 148 183 29 130 94 170 51 61 59 44 | 44 188 163 169 17 13 43 114 173 142 154 103 129 181 105 157 148 182 101 110 66 176 49 45 | 45 156 80 149 58 178 53 108 68 56 125 15 93 75 135 174 198 81 166 113 100 19 89 35 97 38 46 | 46 193 58 86 122 155 8 175 160 99 127 67 14 150 144 126 146 34 131 55 38 196 47 | 47 123 10 109 41 17 12 43 116 59 33 13 2 187 165 88 117 29 30 176 147 180 101 130 194 50 94 152 70 48 | 48 180 128 188 197 105 51 94 190 116 29 183 114 153 33 16 49 3 63 184 17 141 168 179 162 11 66 83 193 49 | 49 48 123 10 186 141 41 168 3 148 142 179 21 136 109 44 117 17 103 187 74 50 | 50 165 123 10 188 36 169 24 187 12 65 29 167 47 21 134 130 111 168 77 116 138 106 66 30 51 | 51 165 48 109 141 163 159 92 190 143 2 21 138 43 59 192 117 16 184 104 169 52 | 52 37 178 8 6 15 200 133 80 102 96 40 119 164 166 127 151 20 42 7 26 76 18 73 99 78 25 132 139 191 150 34 53 | 53 156 122 102 193 137 133 42 62 45 64 60 78 160 132 155 56 144 131 196 178 125 8 32 113 22 98 121 198 24 54 | 54 123 187 12 43 168 65 129 130 147 95 41 61 59 141 3 138 114 199 66 110 55 | 55 68 56 125 113 73 78 200 46 131 85 107 89 185 60 84 4 35 99 171 71 20 23 56 | 56 193 122 53 108 45 55 18 125 86 171 79 6 85 133 80 140 96 31 107 20 32 87 120 42 73 84 22 112 196 7 57 | 57 79 155 158 76 84 22 75 121 85 191 100 97 15 37 102 69 38 64 195 145 23 58 | 58 15 146 107 193 140 84 144 86 14 150 26 60 46 166 80 87 139 195 126 45 37 27 102 62 32 175 39 124 23 93 188 59 | 59 186 163 187 47 168 92 143 147 157 54 51 61 199 43 103 63 184 16 188 197 60 | 60 58 86 178 53 171 125 39 144 146 73 124 4 93 32 99 158 132 80 91 96 75 174 55 196 61 | 61 188 116 41 114 183 28 77 54 36 163 187 147 179 65 63 190 43 186 59 189 62 | 62 193 185 79 53 171 102 146 84 198 14 58 137 8 166 175 32 113 18 115 196 42 200 132 121 19 112 133 172 34 63 | 63 48 24 116 183 111 167 21 162 90 181 147 105 106 101 33 123 153 184 128 168 61 59 64 | 64 91 149 122 53 8 120 113 124 119 25 132 131 193 121 144 68 185 108 175 107 57 65 | 65 186 17 12 114 82 3 66 159 167 197 50 101 176 94 54 134 41 165 157 194 180 77 103 74 61 66 | 66 188 36 116 3 65 183 72 180 77 16 136 177 82 159 28 95 48 50 187 21 44 54 176 67 | 67 91 156 102 68 175 131 144 15 18 146 119 20 200 46 112 139 75 80 86 137 68 | 68 122 171 55 78 175 96 75 71 93 118 195 115 67 79 45 158 15 120 155 193 87 146 81 25 64 23 69 | 69 91 108 125 131 81 75 85 174 145 89 27 200 35 156 1 98 86 23 191 127 31 57 70 | 70 165 123 163 153 12 43 168 3 114 82 148 190 129 74 176 47 110 181 41 30 71 | 71 193 79 171 68 124 98 120 73 75 93 151 108 89 155 19 96 22 119 7 125 85 127 40 55 140 31 72 | 72 109 169 24 116 17 114 182 190 141 186 192 28 104 13 66 165 162 36 159 77 110 129 130 181 73 | 73 91 80 27 160 4 20 100 56 193 60 38 18 25 172 76 14 55 52 149 96 78 71 195 127 5 112 97 93 74 | 74 88 104 197 111 130 95 11 138 123 77 159 65 179 94 165 70 141 16 153 136 83 49 75 | 75 91 79 27 171 68 158 87 81 22 119 71 166 57 60 35 160 69 175 26 193 45 127 67 126 89 20 5 31 198 6 76 | 76 37 178 175 120 122 57 52 34 4 156 98 115 133 131 171 149 85 38 174 39 73 99 14 140 35 135 172 9 7 6 77 | 77 24 116 17 72 190 110 36 173 143 94 65 29 61 154 2 161 90 66 159 28 128 117 11 50 138 74 30 78 | 78 156 80 53 164 68 131 144 107 73 195 55 175 1 126 7 149 171 81 91 52 124 40 9 79 | 79 80 37 158 40 75 108 198 25 62 42 7 86 57 102 122 145 175 71 1 35 164 68 118 56 144 200 139 20 112 135 172 163 80 | 80 91 144 100 118 45 78 139 112 149 98 113 87 195 124 85 73 119 19 79 99 58 56 52 146 81 4 60 137 67 126 145 97 34 134 81 | 81 86 27 120 39 131 40 132 25 69 96 26 127 108 75 68 135 98 80 115 149 78 22 4 45 172 82 | 82 161 186 109 153 43 159 114 101 104 70 29 197 192 116 148 65 152 184 13 154 92 110 130 11 147 66 176 83 | 83 17 13 153 88 111 90 117 95 11 33 147 28 109 199 48 74 167 182 154 101 84 | 84 149 58 86 178 171 62 175 113 26 135 96 198 39 19 57 144 37 118 32 56 119 4 98 25 200 150 55 85 | 85 156 80 185 155 102 56 158 39 76 15 69 38 150 175 118 137 71 35 120 57 55 135 86 | 86 58 84 120 81 112 37 60 46 185 193 38 125 118 175 149 99 108 126 133 102 79 56 144 67 69 31 109 87 | 87 80 149 58 118 25 75 126 115 68 178 37 200 32 40 164 56 42 193 107 1 39 113 145 89 172 6 34 93 88 | 88 36 116 12 47 165 168 29 83 159 154 74 148 92 176 180 33 110 194 167 17 114 173 16 11 89 | 89 37 27 102 32 42 18 99 71 151 19 55 75 98 131 69 45 31 38 195 87 20 135 115 90 | 90 163 116 13 173 28 110 190 77 129 117 130 10 179 92 134 194 21 63 83 157 94 152 199 91 | 91 126 14 75 135 107 80 102 67 160 158 144 23 64 155 4 198 40 9 73 69 193 185 149 164 42 78 60 98 19 1 165 92 | 92 161 109 163 187 88 186 141 51 117 197 59 173 192 82 29 143 116 41 30 111 148 129 90 194 152 170 93 | 93 68 99 71 60 45 150 145 98 25 87 122 178 185 7 144 4 22 73 58 112 94 | 94 48 163 65 173 182 154 77 21 117 11 147 74 189 43 114 47 177 192 104 90 95 | 95 123 141 169 17 168 114 179 21 33 165 167 177 41 103 83 199 129 182 188 74 66 157 152 54 176 96 | 96 171 164 68 56 52 18 73 84 81 124 22 71 60 126 150 20 97 38 149 158 196 115 97 | 97 185 149 37 178 122 108 118 32 131 1 31 140 73 34 45 25 80 133 57 96 98 | 98 80 171 164 158 120 76 99 81 71 37 91 151 144 172 140 150 160 121 84 53 139 89 69 31 133 93 99 | 99 80 86 178 122 118 125 52 193 32 174 46 113 98 93 89 150 102 76 100 124 4 60 55 5 38 196 100 | 100 80 185 149 27 8 113 131 15 73 99 22 4 200 45 102 172 57 164 38 39 1 112 9 101 | 101 165 10 188 109 141 163 187 12 168 82 65 148 180 47 167 2 162 169 192 30 179 11 44 83 170 63 102 | 102 91 86 79 53 171 155 67 113 39 137 158 196 166 120 42 89 58 5 119 85 62 52 146 99 121 100 57 103 | 103 161 188 186 184 153 159 167 189 2 168 13 29 104 142 33 65 197 117 148 44 95 181 59 49 104 | 104 134 188 186 141 184 41 187 168 114 82 148 192 194 154 74 3 190 161 105 163 72 103 94 170 51 105 | 105 165 48 161 116 159 104 21 129 63 44 169 106 142 190 181 143 179 157 173 188 199 176 106 | 106 36 163 169 184 41 159 29 197 111 16 179 162 105 138 148 50 165 63 173 109 107 | 107 91 58 56 125 158 87 191 133 9 38 122 164 175 135 4 35 14 7 185 78 18 146 151 26 64 126 55 20 112 198 172 108 | 108 86 178 79 164 37 25 195 144 120 198 26 56 19 132 69 193 115 45 172 97 155 8 81 71 166 139 174 64 31 41 109 | 109 10 47 116 12 128 51 167 180 179 33 123 101 142 92 143 199 154 3 72 82 141 17 168 114 173 183 148 189 11 181 106 83 152 49 86 110 | 110 165 186 36 163 169 43 88 168 33 138 147 13 167 189 184 134 72 90 188 82 77 44 54 70 111 | 111 41 92 114 162 188 129 187 170 152 83 142 74 157 16 13 138 186 106 63 184 28 21 50 30 192 112 | 112 193 80 86 27 137 174 67 5 79 198 132 127 42 131 100 73 107 56 135 62 7 93 113 | 113 156 80 149 171 102 62 39 133 84 87 198 1 53 64 55 172 122 100 42 14 160 99 124 137 45 19 145 7 114 | 114 48 104 136 16 61 72 181 128 82 88 138 109 129 70 192 3 153 65 95 44 111 28 21 11 94 54 115 | 115 185 37 27 108 68 62 87 120 76 81 22 25 151 139 191 140 9 89 96 18 116 | 116 48 188 109 24 157 61 41 181 128 66 88 63 152 189 168 90 105 72 77 10 13 47 82 173 92 142 28 180 2 21 117 50 33 136 164 117 | 117 17 47 92 16 179 2 103 90 194 189 192 94 143 170 162 83 116 129 184 77 138 152 51 49 118 | 118 193 156 80 86 155 68 196 145 40 4 97 79 5 99 87 149 174 34 137 166 131 15 160 84 121 85 119 | 119 80 178 102 52 160 124 84 185 6 22 67 174 8 121 133 5 75 64 15 150 71 151 145 20 120 | 120 185 86 171 108 102 68 200 193 126 64 160 32 150 6 115 98 81 56 191 76 124 71 139 85 195 135 121 | 121 156 185 37 32 15 146 22 119 4 98 151 57 62 126 53 139 40 102 35 118 64 135 133 122 | 122 156 146 23 99 196 46 14 56 53 175 164 20 68 39 195 126 97 40 34 64 79 27 155 113 76 131 15 42 107 166 151 9 93 36 123 | 123 165 194 50 70 95 11 153 30 24 17 49 47 54 2 189 147 199 3 188 197 186 109 41 29 129 130 128 74 136 63 156 124 | 124 193 80 125 32 146 99 23 5 60 113 120 191 6 58 64 119 71 37 78 96 137 125 | 125 37 86 56 4 133 69 178 132 53 172 45 60 151 40 198 55 35 107 99 124 71 137 127 23 126 | 126 91 58 86 122 155 87 120 146 78 200 121 19 80 20 137 75 96 107 18 156 46 135 127 | 127 37 178 32 52 131 160 81 4 25 191 125 38 71 15 8 42 75 46 174 73 14 69 112 172 9 34 128 | 128 48 134 161 109 116 187 114 183 16 179 189 130 181 142 123 138 2 136 77 152 63 129 | 129 165 184 41 153 114 148 111 177 16 180 44 29 123 54 173 72 92 70 199 105 90 117 95 157 130 | 130 186 169 24 3 154 189 21 136 72 82 74 190 11 47 13 173 54 181 43 123 90 128 50 138 30 176 131 | 131 193 53 76 78 22 69 97 118 178 122 140 81 34 164 8 100 127 67 31 6 42 146 200 195 26 64 46 55 89 112 132 | 132 185 149 53 171 108 125 18 81 60 25 139 191 178 64 52 9 62 22 40 164 35 112 133 | 133 86 53 56 125 8 52 113 76 107 119 195 97 156 98 121 62 140 26 175 9 134 | 134 153 11 17 182 165 197 138 173 24 28 104 128 29 2 167 152 183 3 162 154 186 13 65 142 110 90 50 33 157 80 135 | 135 91 171 164 107 84 81 45 5 35 112 120 15 151 85 76 79 178 121 126 89 136 | 136 165 36 187 3 114 173 190 130 128 66 74 152 123 154 116 28 49 153 16 169 137 | 137 156 185 53 155 102 118 62 166 175 200 151 112 113 14 124 80 146 35 125 34 85 67 126 145 172 138 | 138 134 186 153 114 111 142 110 179 21 128 130 117 197 169 77 13 74 51 180 50 106 54 139 | 139 80 58 27 164 132 121 108 115 140 31 79 98 15 160 52 26 171 39 195 120 67 14 35 196 34 140 | 140 185 58 56 8 175 131 144 18 4 166 98 139 1 195 22 156 71 76 178 115 97 133 141 | 141 109 104 184 2 143 188 51 49 33 197 48 176 95 159 148 101 154 13 170 190 36 43 3 92 72 16 28 167 180 147 74 54 178 142 | 142 161 109 169 12 183 111 163 187 162 180 16 165 116 184 138 44 13 49 134 143 177 103 128 181 105 192 143 | 143 165 161 109 141 24 184 168 92 142 154 180 51 147 179 176 183 189 59 159 167 77 117 105 152 144 | 144 91 80 58 178 27 53 164 108 8 158 60 79 67 155 78 140 7 86 26 174 84 98 64 19 46 145 6 93 145 | 145 178 79 155 118 18 151 69 39 113 42 119 93 80 144 87 15 137 23 158 166 5 57 172 146 | 146 149 58 37 122 62 60 68 107 31 67 172 195 121 131 102 185 174 124 126 80 22 137 46 5 147 | 147 123 186 36 47 183 29 182 197 16 167 110 143 168 83 82 141 63 94 54 59 157 170 61 148 | 148 10 188 186 141 163 12 43 88 82 109 192 70 161 30 129 24 92 49 177 29 104 197 154 101 103 162 181 106 44 176 149 | 149 156 80 200 146 15 185 87 91 100 45 37 178 18 32 64 132 97 84 150 113 86 118 76 73 81 78 22 31 96 23 161 150 | 150 149 58 8 175 120 39 99 119 166 98 200 85 14 4 46 96 84 22 93 52 151 | 151 125 52 160 71 166 98 137 145 122 171 119 193 175 32 121 107 115 18 39 89 135 196 152 | 152 134 161 36 116 41 17 82 111 28 128 157 13 92 47 143 117 109 90 95 136 170 153 | 153 165 48 123 134 10 186 138 187 103 82 70 163 129 188 170 173 24 83 167 41 43 3 114 154 180 74 136 63 30 154 | 154 134 10 109 141 36 41 88 159 82 104 143 148 197 44 13 94 130 162 177 153 167 77 2 83 136 170 155 | 155 91 185 53 164 108 145 171 200 6 122 8 9 85 57 1 137 126 102 118 46 68 158 39 144 160 71 172 156 | 156 7 53 113 45 14 193 122 40 67 19 121 22 118 78 5 137 166 149 32 85 178 27 158 76 126 140 69 133 9 23 123 157 | 157 184 116 13 3 65 111 90 105 187 147 152 134 59 95 186 197 44 170 129 21 158 | 158 91 193 79 27 102 68 32 75 156 107 185 144 4 57 39 155 98 171 85 25 175 60 145 38 96 159 | 159 188 141 36 24 13 12 88 103 105 179 177 17 3 182 51 82 28 161 154 106 65 183 72 143 77 66 74 160 | 160 91 185 53 32 120 155 6 9 18 127 171 118 113 119 151 26 46 195 200 73 98 75 139 40 1 5 198 38 161 | 161 165 10 24 173 142 182 162 92 13 152 33 82 189 43 143 128 103 186 105 12 188 184 41 17 159 148 104 180 77 194 170 149 162 | 162 134 161 188 186 36 24 173 182 111 142 72 154 101 48 148 2 179 106 63 41 117 163 | 163 177 92 10 148 101 44 169 59 110 188 17 51 90 186 94 11 24 70 106 182 41 153 187 104 142 190 61 79 164 | 164 185 37 122 175 139 144 91 35 19 96 98 78 155 1 108 198 42 135 79 195 8 52 87 131 107 166 132 100 34 116 165 | 165 30 105 36 101 167 183 43 50 70 189 181 190 161 123 136 51 143 129 153 110 134 169 13 47 88 65 142 72 95 106 74 91 166 | 166 156 58 27 102 118 62 52 191 140 164 40 122 151 108 75 174 137 196 150 34 200 45 26 145 6 167 | 167 165 134 109 24 17 153 187 88 168 65 182 177 154 16 194 141 103 50 147 63 110 101 179 143 21 95 83 168 | 168 36 169 116 88 48 70 30 33 101 104 109 110 143 181 167 54 199 49 59 95 177 180 103 50 147 63 169 | 169 163 50 184 12 176 106 41 194 173 168 110 142 44 95 130 24 165 182 72 177 197 28 101 138 105 136 51 27 170 | 170 10 186 141 17 13 153 111 117 157 92 161 152 147 104 179 154 43 101 36 199 171 | 171 34 60 68 31 20 42 62 4 120 71 32 135 113 175 84 102 132 96 98 75 155 56 8 158 76 160 78 151 139 55 184 172 | 172 185 108 125 113 146 73 98 174 100 155 81 79 76 127 87 137 107 19 62 145 173 | 173 134 10 161 169 13 153 109 162 44 21 88 182 3 190 179 136 90 16 116 94 92 28 77 129 130 105 106 174 | 174 27 118 175 76 144 15 146 99 119 166 45 32 19 172 191 60 108 37 69 112 127 175 | 175 86 122 79 171 164 68 62 84 140 5 40 196 46 174 150 67 58 76 193 158 107 78 22 137 75 151 85 195 64 1 133 176 | 176 141 169 13 47 88 3 65 183 177 143 148 82 105 130 66 181 44 21 182 95 70 177 | 177 10 36 163 169 159 29 148 190 12 199 167 176 180 2 192 168 142 41 179 129 154 28 21 95 66 94 178 | 178 149 76 19 52 127 108 45 156 60 198 99 37 144 7 97 145 84 119 42 191 53 125 8 87 131 18 25 132 195 140 135 93 141 179 | 179 10 109 36 159 173 177 49 117 12 48 101 189 2 138 128 95 106 28 167 16 143 162 90 105 74 170 199 30 61 180 | 180 48 109 17 88 142 177 16 65 194 36 153 116 161 66 143 141 129 47 168 21 101 181 138 181 | 181 165 188 184 116 13 168 114 182 130 128 44 103 148 63 29 142 180 17 109 72 105 176 70 182 | 182 134 10 161 163 169 184 13 159 173 183 147 189 162 181 12 72 167 94 199 192 2 95 44 83 176 183 | 183 165 48 134 188 186 63 33 147 43 61 109 142 159 66 41 128 182 176 190 184 143 189 184 | 184 48 10 141 169 24 143 41 161 181 36 129 197 104 186 182 28 106 157 103 199 82 183 111 142 110 117 63 51 59 171 185 | 185 193 140 8 97 7 121 160 155 85 172 91 100 164 132 25 120 20 62 137 115 149 86 32 158 107 146 119 64 55 93 10 186 | 186 161 104 199 162 148 110 138 183 153 103 192 82 130 123 59 49 147 134 65 170 163 184 187 92 197 111 72 157 61 37 187 | 187 24 153 186 92 189 54 33 59 21 167 163 101 136 50 197 16 104 128 192 30 47 111 142 66 157 61 49 188 | 188 48 123 50 104 36 101 148 66 161 44 28 21 162 116 183 103 159 181 61 29 141 163 153 111 110 190 95 105 59 58 189 | 189 165 123 10 161 116 41 187 43 29 182 197 16 110 179 143 12 183 103 199 109 130 128 194 117 94 61 190 | 190 165 48 10 141 13 43 3 173 183 104 177 72 36 77 188 90 136 51 163 70 130 105 61 191 | 191 193 37 178 8 32 120 15 42 107 18 124 166 132 174 20 52 57 31 115 127 1 69 9 23 192 | 192 186 187 12 114 82 92 29 148 104 182 177 72 28 101 21 117 94 51 111 142 193 | 193 26 112 191 62 195 25 91 39 71 158 131 46 5 38 37 185 18 118 124 56 156 58 86 53 108 68 175 87 120 15 42 73 99 4 75 151 64 35 48 194 | 194 123 169 43 88 65 29 104 16 167 180 90 189 161 199 47 92 3 12 17 117 195 | 195 193 80 58 122 164 108 68 160 146 78 139 23 120 178 133 73 175 37 131 9 19 89 140 57 196 | 196 122 53 102 118 62 175 15 166 31 9 37 6 99 151 56 139 46 1 96 60 197 | 197 48 123 134 141 184 187 82 65 92 106 148 147 199 29 17 30 189 186 74 169 154 21 103 138 157 59 198 | 198 91 37 178 79 164 108 125 62 113 18 84 45 26 112 35 107 160 53 1 75 199 | 199 123 186 109 184 43 168 29 182 197 177 189 129 194 95 83 170 54 105 90 179 30 59 200 | 200 149 155 52 87 120 39 160 137 27 79 131 100 25 55 23 126 84 166 150 62 67 1 69 35 201 | -------------------------------------------------------------------------------- /Programming Assignment 4/random.py: -------------------------------------------------------------------------------- 1 | """Random variable generators. 2 | 3 | integers 4 | -------- 5 | uniform within range 6 | 7 | sequences 8 | --------- 9 | pick random element 10 | pick random sample 11 | generate random permutation 12 | 13 | distributions on the real line: 14 | ------------------------------ 15 | uniform 16 | triangular 17 | normal (Gaussian) 18 | lognormal 19 | negative exponential 20 | gamma 21 | beta 22 | pareto 23 | Weibull 24 | 25 | distributions on the circle (angles 0 to 2pi) 26 | --------------------------------------------- 27 | circular uniform 28 | von Mises 29 | 30 | General notes on the underlying Mersenne Twister core generator: 31 | 32 | * The period is 2**19937-1. 33 | * It is one of the most extensively tested generators in existence. 34 | * Without a direct way to compute N steps forward, the semantics of 35 | jumpahead(n) are weakened to simply jump to another distant state and rely 36 | on the large period to avoid overlapping sequences. 37 | * The random() method is implemented in C, executes in a single Python step, 38 | and is, therefore, threadsafe. 39 | 40 | """ 41 | 42 | from __future__ import division 43 | from warnings import warn as _warn 44 | from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType 45 | from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil 46 | from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin 47 | from os import urandom as _urandom 48 | from binascii import hexlify as _hexlify 49 | 50 | __all__ = ["Random","seed","random","uniform","randint","choice","sample", 51 | "randrange","shuffle","normalvariate","lognormvariate", 52 | "expovariate","vonmisesvariate","gammavariate","triangular", 53 | "gauss","betavariate","paretovariate","weibullvariate", 54 | "getstate","setstate","jumpahead", "WichmannHill", "getrandbits", 55 | "SystemRandom"] 56 | 57 | NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0) 58 | TWOPI = 2.0*_pi 59 | LOG4 = _log(4.0) 60 | SG_MAGICCONST = 1.0 + _log(4.5) 61 | BPF = 53 # Number of bits in a float 62 | RECIP_BPF = 2**-BPF 63 | 64 | 65 | # Translated by Guido van Rossum from C source provided by 66 | # Adrian Baddeley. Adapted by Raymond Hettinger for use with 67 | # the Mersenne Twister and os.urandom() core generators. 68 | 69 | import _random 70 | 71 | class Random(_random.Random): 72 | """Random number generator base class used by bound module functions. 73 | 74 | Used to instantiate instances of Random to get generators that don't 75 | share state. Especially useful for multi-threaded programs, creating 76 | a different instance of Random for each thread, and using the jumpahead() 77 | method to ensure that the generated sequences seen by each thread don't 78 | overlap. 79 | 80 | Class Random can also be subclassed if you want to use a different basic 81 | generator of your own devising: in that case, override the following 82 | methods: random(), seed(), getstate(), setstate() and jumpahead(). 83 | Optionally, implement a getrandbits() method so that randrange() can cover 84 | arbitrarily large ranges. 85 | 86 | """ 87 | 88 | VERSION = 3 # used by getstate/setstate 89 | 90 | def __init__(self, x=None): 91 | """Initialize an instance. 92 | 93 | Optional argument x controls seeding, as for Random.seed(). 94 | """ 95 | 96 | self.seed(x) 97 | self.gauss_next = None 98 | 99 | def seed(self, a=None): 100 | """Initialize internal state from hashable object. 101 | 102 | None or no argument seeds from current time or from an operating 103 | system specific randomness source if available. 104 | 105 | If a is not None or an int or long, hash(a) is used instead. 106 | """ 107 | 108 | if a is None: 109 | try: 110 | a = long(_hexlify(_urandom(16)), 16) 111 | except NotImplementedError: 112 | import time 113 | a = long(time.time() * 256) # use fractional seconds 114 | 115 | super(Random, self).seed(a) 116 | self.gauss_next = None 117 | 118 | def getstate(self): 119 | """Return internal state; can be passed to setstate() later.""" 120 | return self.VERSION, super(Random, self).getstate(), self.gauss_next 121 | 122 | def setstate(self, state): 123 | """Restore internal state from object returned by getstate().""" 124 | version = state[0] 125 | if version == 3: 126 | version, internalstate, self.gauss_next = state 127 | super(Random, self).setstate(internalstate) 128 | elif version == 2: 129 | version, internalstate, self.gauss_next = state 130 | # In version 2, the state was saved as signed ints, which causes 131 | # inconsistencies between 32/64-bit systems. The state is 132 | # really unsigned 32-bit ints, so we convert negative ints from 133 | # version 2 to positive longs for version 3. 134 | try: 135 | internalstate = tuple( long(x) % (2**32) for x in internalstate ) 136 | except ValueError, e: 137 | raise TypeError, e 138 | super(Random, self).setstate(internalstate) 139 | else: 140 | raise ValueError("state with version %s passed to " 141 | "Random.setstate() of version %s" % 142 | (version, self.VERSION)) 143 | 144 | ## ---- Methods below this point do not need to be overridden when 145 | ## ---- subclassing for the purpose of using a different core generator. 146 | 147 | ## -------------------- pickle support ------------------- 148 | 149 | def __getstate__(self): # for pickle 150 | return self.getstate() 151 | 152 | def __setstate__(self, state): # for pickle 153 | self.setstate(state) 154 | 155 | def __reduce__(self): 156 | return self.__class__, (), self.getstate() 157 | 158 | ## -------------------- integer methods ------------------- 159 | 160 | def randrange(self, start, stop=None, step=1, int=int, default=None, 161 | maxwidth=1L< 0: 176 | if istart >= maxwidth: 177 | return self._randbelow(istart) 178 | return int(self.random() * istart) 179 | raise ValueError, "empty range for randrange()" 180 | 181 | # stop argument supplied. 182 | istop = int(stop) 183 | if istop != stop: 184 | raise ValueError, "non-integer stop for randrange()" 185 | width = istop - istart 186 | if step == 1 and width > 0: 187 | # Note that 188 | # int(istart + self.random()*width) 189 | # instead would be incorrect. For example, consider istart 190 | # = -2 and istop = 0. Then the guts would be in 191 | # -2.0 to 0.0 exclusive on both ends (ignoring that random() 192 | # might return 0.0), and because int() truncates toward 0, the 193 | # final result would be -1 or 0 (instead of -2 or -1). 194 | # istart + int(self.random()*width) 195 | # would also be incorrect, for a subtler reason: the RHS 196 | # can return a long, and then randrange() would also return 197 | # a long, but we're supposed to return an int (for backward 198 | # compatibility). 199 | 200 | if width >= maxwidth: 201 | return int(istart + self._randbelow(width)) 202 | return int(istart + int(self.random()*width)) 203 | if step == 1: 204 | raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width) 205 | 206 | # Non-unit step argument supplied. 207 | istep = int(step) 208 | if istep != step: 209 | raise ValueError, "non-integer step for randrange()" 210 | if istep > 0: 211 | n = (width + istep - 1) // istep 212 | elif istep < 0: 213 | n = (width + istep + 1) // istep 214 | else: 215 | raise ValueError, "zero step for randrange()" 216 | 217 | if n <= 0: 218 | raise ValueError, "empty range for randrange()" 219 | 220 | if n >= maxwidth: 221 | return istart + istep*self._randbelow(n) 222 | return istart + istep*int(self.random() * n) 223 | 224 | def randint(self, a, b): 225 | """Return random integer in range [a, b], including both end points. 226 | """ 227 | 228 | return self.randrange(a, b+1) 229 | 230 | def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L< n-1 > 2**(k-2) 248 | r = getrandbits(k) 249 | while r >= n: 250 | r = getrandbits(k) 251 | return r 252 | if n >= _maxwidth: 253 | _warn("Underlying random() generator does not supply \n" 254 | "enough bits to choose from a population range this large") 255 | return int(self.random() * n) 256 | 257 | ## -------------------- sequence methods ------------------- 258 | 259 | def choice(self, seq): 260 | """Choose a random element from a non-empty sequence.""" 261 | return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty 262 | 263 | def shuffle(self, x, random=None, int=int): 264 | """x, random=random.random -> shuffle list x in place; return None. 265 | 266 | Optional arg random is a 0-argument function returning a random 267 | float in [0.0, 1.0); by default, the standard random.random. 268 | """ 269 | 270 | if random is None: 271 | random = self.random 272 | for i in reversed(xrange(1, len(x))): 273 | # pick an element in x[:i+1] with which to exchange x[i] 274 | j = int(random() * (i+1)) 275 | x[i], x[j] = x[j], x[i] 276 | 277 | def sample(self, population, k): 278 | """Chooses k unique random elements from a population sequence. 279 | 280 | Returns a new list containing elements from the population while 281 | leaving the original population unchanged. The resulting list is 282 | in selection order so that all sub-slices will also be valid random 283 | samples. This allows raffle winners (the sample) to be partitioned 284 | into grand prize and second place winners (the subslices). 285 | 286 | Members of the population need not be hashable or unique. If the 287 | population contains repeats, then each occurrence is a possible 288 | selection in the sample. 289 | 290 | To choose a sample in a range of integers, use xrange as an argument. 291 | This is especially fast and space efficient for sampling from a 292 | large population: sample(xrange(10000000), 60) 293 | """ 294 | 295 | # XXX Although the documentation says `population` is "a sequence", 296 | # XXX attempts are made to cater to any iterable with a __len__ 297 | # XXX method. This has had mixed success. Examples from both 298 | # XXX sides: sets work fine, and should become officially supported; 299 | # XXX dicts are much harder, and have failed in various subtle 300 | # XXX ways across attempts. Support for mapping types should probably 301 | # XXX be dropped (and users should pass mapping.keys() or .values() 302 | # XXX explicitly). 303 | 304 | # Sampling without replacement entails tracking either potential 305 | # selections (the pool) in a list or previous selections in a set. 306 | 307 | # When the number of selections is small compared to the 308 | # population, then tracking selections is efficient, requiring 309 | # only a small set and an occasional reselection. For 310 | # a larger number of selections, the pool tracking method is 311 | # preferred since the list takes less space than the 312 | # set and it doesn't suffer from frequent reselections. 313 | 314 | n = len(population) 315 | if not 0 <= k <= n: 316 | raise ValueError, "sample larger than population" 317 | random = self.random 318 | _int = int 319 | result = [None] * k 320 | setsize = 21 # size of a small set minus size of an empty list 321 | if k > 5: 322 | setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets 323 | if n <= setsize or hasattr(population, "keys"): 324 | # An n-length list is smaller than a k-length set, or this is a 325 | # mapping type so the other algorithm wouldn't work. 326 | pool = list(population) 327 | for i in xrange(k): # invariant: non-selected at [0,n-i) 328 | j = _int(random() * (n-i)) 329 | result[i] = pool[j] 330 | pool[j] = pool[n-i-1] # move non-selected item into vacancy 331 | else: 332 | try: 333 | selected = set() 334 | selected_add = selected.add 335 | for i in xrange(k): 336 | j = _int(random() * n) 337 | while j in selected: 338 | j = _int(random() * n) 339 | selected_add(j) 340 | result[i] = population[j] 341 | except (TypeError, KeyError): # handle (at least) sets 342 | if isinstance(population, list): 343 | raise 344 | return self.sample(tuple(population), k) 345 | return result 346 | 347 | ## -------------------- real-valued distributions ------------------- 348 | 349 | ## -------------------- uniform distribution ------------------- 350 | 351 | def uniform(self, a, b): 352 | """Get a random number in the range [a, b).""" 353 | return a + (b-a) * self.random() 354 | 355 | ## -------------------- triangular -------------------- 356 | 357 | def triangular(self, low=0.0, high=1.0, mode=None): 358 | """Triangular distribution. 359 | 360 | Continuous distribution bounded by given lower and upper limits, 361 | and having a given mode value in-between. 362 | 363 | http://en.wikipedia.org/wiki/Triangular_distribution 364 | 365 | """ 366 | u = self.random() 367 | c = 0.5 if mode is None else (mode - low) / (high - low) 368 | if u > c: 369 | u = 1.0 - u 370 | c = 1.0 - c 371 | low, high = high, low 372 | return low + (high - low) * (u * c) ** 0.5 373 | 374 | ## -------------------- normal distribution -------------------- 375 | 376 | def normalvariate(self, mu, sigma): 377 | """Normal distribution. 378 | 379 | mu is the mean, and sigma is the standard deviation. 380 | 381 | """ 382 | # mu = mean, sigma = standard deviation 383 | 384 | # Uses Kinderman and Monahan method. Reference: Kinderman, 385 | # A.J. and Monahan, J.F., "Computer generation of random 386 | # variables using the ratio of uniform deviates", ACM Trans 387 | # Math Software, 3, (1977), pp257-260. 388 | 389 | random = self.random 390 | while 1: 391 | u1 = random() 392 | u2 = 1.0 - random() 393 | z = NV_MAGICCONST*(u1-0.5)/u2 394 | zz = z*z/4.0 395 | if zz <= -_log(u2): 396 | break 397 | return mu + z*sigma 398 | 399 | ## -------------------- lognormal distribution -------------------- 400 | 401 | def lognormvariate(self, mu, sigma): 402 | """Log normal distribution. 403 | 404 | If you take the natural logarithm of this distribution, you'll get a 405 | normal distribution with mean mu and standard deviation sigma. 406 | mu can have any value, and sigma must be greater than zero. 407 | 408 | """ 409 | return _exp(self.normalvariate(mu, sigma)) 410 | 411 | ## -------------------- exponential distribution -------------------- 412 | 413 | def expovariate(self, lambd): 414 | """Exponential distribution. 415 | 416 | lambd is 1.0 divided by the desired mean. It should be 417 | nonzero. (The parameter would be called "lambda", but that is 418 | a reserved word in Python.) Returned values range from 0 to 419 | positive infinity if lambd is positive, and from negative 420 | infinity to 0 if lambd is negative. 421 | 422 | """ 423 | # lambd: rate lambd = 1/mean 424 | # ('lambda' is a Python reserved word) 425 | 426 | random = self.random 427 | u = random() 428 | while u <= 1e-7: 429 | u = random() 430 | return -_log(u)/lambd 431 | 432 | ## -------------------- von Mises distribution -------------------- 433 | 434 | def vonmisesvariate(self, mu, kappa): 435 | """Circular data distribution. 436 | 437 | mu is the mean angle, expressed in radians between 0 and 2*pi, and 438 | kappa is the concentration parameter, which must be greater than or 439 | equal to zero. If kappa is equal to zero, this distribution reduces 440 | to a uniform random angle over the range 0 to 2*pi. 441 | 442 | """ 443 | # mu: mean angle (in radians between 0 and 2*pi) 444 | # kappa: concentration parameter kappa (>= 0) 445 | # if kappa = 0 generate uniform random angle 446 | 447 | # Based upon an algorithm published in: Fisher, N.I., 448 | # "Statistical Analysis of Circular Data", Cambridge 449 | # University Press, 1993. 450 | 451 | # Thanks to Magnus Kessler for a correction to the 452 | # implementation of step 4. 453 | 454 | random = self.random 455 | if kappa <= 1e-6: 456 | return TWOPI * random() 457 | 458 | a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa) 459 | b = (a - _sqrt(2.0 * a))/(2.0 * kappa) 460 | r = (1.0 + b * b)/(2.0 * b) 461 | 462 | while 1: 463 | u1 = random() 464 | 465 | z = _cos(_pi * u1) 466 | f = (1.0 + r * z)/(r + z) 467 | c = kappa * (r - f) 468 | 469 | u2 = random() 470 | 471 | if u2 < c * (2.0 - c) or u2 <= c * _exp(1.0 - c): 472 | break 473 | 474 | u3 = random() 475 | if u3 > 0.5: 476 | theta = (mu % TWOPI) + _acos(f) 477 | else: 478 | theta = (mu % TWOPI) - _acos(f) 479 | 480 | return theta 481 | 482 | ## -------------------- gamma distribution -------------------- 483 | 484 | def gammavariate(self, alpha, beta): 485 | """Gamma distribution. Not the gamma function! 486 | 487 | Conditions on the parameters are alpha > 0 and beta > 0. 488 | 489 | """ 490 | 491 | # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 492 | 493 | # Warning: a few older sources define the gamma distribution in terms 494 | # of alpha > -1.0 495 | if alpha <= 0.0 or beta <= 0.0: 496 | raise ValueError, 'gammavariate: alpha and beta must be > 0.0' 497 | 498 | random = self.random 499 | if alpha > 1.0: 500 | 501 | # Uses R.C.H. Cheng, "The generation of Gamma 502 | # variables with non-integral shape parameters", 503 | # Applied Statistics, (1977), 26, No. 1, p71-74 504 | 505 | ainv = _sqrt(2.0 * alpha - 1.0) 506 | bbb = alpha - LOG4 507 | ccc = alpha + ainv 508 | 509 | while 1: 510 | u1 = random() 511 | if not 1e-7 < u1 < .9999999: 512 | continue 513 | u2 = 1.0 - random() 514 | v = _log(u1/(1.0-u1))/ainv 515 | x = alpha*_exp(v) 516 | z = u1*u1*u2 517 | r = bbb+ccc*v-x 518 | if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z): 519 | return x * beta 520 | 521 | elif alpha == 1.0: 522 | # expovariate(1) 523 | u = random() 524 | while u <= 1e-7: 525 | u = random() 526 | return -_log(u) * beta 527 | 528 | else: # alpha is between 0 and 1 (exclusive) 529 | 530 | # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle 531 | 532 | while 1: 533 | u = random() 534 | b = (_e + alpha)/_e 535 | p = b*u 536 | if p <= 1.0: 537 | x = p ** (1.0/alpha) 538 | else: 539 | x = -_log((b-p)/alpha) 540 | u1 = random() 541 | if p > 1.0: 542 | if u1 <= x ** (alpha - 1.0): 543 | break 544 | elif u1 <= _exp(-x): 545 | break 546 | return x * beta 547 | 548 | ## -------------------- Gauss (faster alternative) -------------------- 549 | 550 | def gauss(self, mu, sigma): 551 | """Gaussian distribution. 552 | 553 | mu is the mean, and sigma is the standard deviation. This is 554 | slightly faster than the normalvariate() function. 555 | 556 | Not thread-safe without a lock around calls. 557 | 558 | """ 559 | 560 | # When x and y are two variables from [0, 1), uniformly 561 | # distributed, then 562 | # 563 | # cos(2*pi*x)*sqrt(-2*log(1-y)) 564 | # sin(2*pi*x)*sqrt(-2*log(1-y)) 565 | # 566 | # are two *independent* variables with normal distribution 567 | # (mu = 0, sigma = 1). 568 | # (Lambert Meertens) 569 | # (corrected version; bug discovered by Mike Miller, fixed by LM) 570 | 571 | # Multithreading note: When two threads call this function 572 | # simultaneously, it is possible that they will receive the 573 | # same return value. The window is very small though. To 574 | # avoid this, you have to use a lock around all calls. (I 575 | # didn't want to slow this down in the serial case by using a 576 | # lock here.) 577 | 578 | random = self.random 579 | z = self.gauss_next 580 | self.gauss_next = None 581 | if z is None: 582 | x2pi = random() * TWOPI 583 | g2rad = _sqrt(-2.0 * _log(1.0 - random())) 584 | z = _cos(x2pi) * g2rad 585 | self.gauss_next = _sin(x2pi) * g2rad 586 | 587 | return mu + z*sigma 588 | 589 | ## -------------------- beta -------------------- 590 | ## See 591 | ## http://sourceforge.net/bugs/?func=detailbug&bug_id=130030&group_id=5470 592 | ## for Ivan Frohne's insightful analysis of why the original implementation: 593 | ## 594 | ## def betavariate(self, alpha, beta): 595 | ## # Discrete Event Simulation in C, pp 87-88. 596 | ## 597 | ## y = self.expovariate(alpha) 598 | ## z = self.expovariate(1.0/beta) 599 | ## return z/(y+z) 600 | ## 601 | ## was dead wrong, and how it probably got that way. 602 | 603 | def betavariate(self, alpha, beta): 604 | """Beta distribution. 605 | 606 | Conditions on the parameters are alpha > 0 and beta > 0. 607 | Returned values range between 0 and 1. 608 | 609 | """ 610 | 611 | # This version due to Janne Sinkkonen, and matches all the std 612 | # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). 613 | y = self.gammavariate(alpha, 1.) 614 | if y == 0: 615 | return 0.0 616 | else: 617 | return y / (y + self.gammavariate(beta, 1.)) 618 | 619 | ## -------------------- Pareto -------------------- 620 | 621 | def paretovariate(self, alpha): 622 | """Pareto distribution. alpha is the shape parameter.""" 623 | # Jain, pg. 495 624 | 625 | u = 1.0 - self.random() 626 | return 1.0 / pow(u, 1.0/alpha) 627 | 628 | ## -------------------- Weibull -------------------- 629 | 630 | def weibullvariate(self, alpha, beta): 631 | """Weibull distribution. 632 | 633 | alpha is the scale parameter and beta is the shape parameter. 634 | 635 | """ 636 | # Jain, pg. 499; bug fix courtesy Bill Arms 637 | 638 | u = 1.0 - self.random() 639 | return alpha * pow(-_log(u), 1.0/beta) 640 | 641 | ## -------------------- Wichmann-Hill ------------------- 642 | 643 | class WichmannHill(Random): 644 | 645 | VERSION = 1 # used by getstate/setstate 646 | 647 | def seed(self, a=None): 648 | """Initialize internal state from hashable object. 649 | 650 | None or no argument seeds from current time or from an operating 651 | system specific randomness source if available. 652 | 653 | If a is not None or an int or long, hash(a) is used instead. 654 | 655 | If a is an int or long, a is used directly. Distinct values between 656 | 0 and 27814431486575L inclusive are guaranteed to yield distinct 657 | internal states (this guarantee is specific to the default 658 | Wichmann-Hill generator). 659 | """ 660 | 661 | if a is None: 662 | try: 663 | a = long(_hexlify(_urandom(16)), 16) 664 | except NotImplementedError: 665 | import time 666 | a = long(time.time() * 256) # use fractional seconds 667 | 668 | if not isinstance(a, (int, long)): 669 | a = hash(a) 670 | 671 | a, x = divmod(a, 30268) 672 | a, y = divmod(a, 30306) 673 | a, z = divmod(a, 30322) 674 | self._seed = int(x)+1, int(y)+1, int(z)+1 675 | 676 | self.gauss_next = None 677 | 678 | def random(self): 679 | """Get the next random number in the range [0.0, 1.0).""" 680 | 681 | # Wichman-Hill random number generator. 682 | # 683 | # Wichmann, B. A. & Hill, I. D. (1982) 684 | # Algorithm AS 183: 685 | # An efficient and portable pseudo-random number generator 686 | # Applied Statistics 31 (1982) 188-190 687 | # 688 | # see also: 689 | # Correction to Algorithm AS 183 690 | # Applied Statistics 33 (1984) 123 691 | # 692 | # McLeod, A. I. (1985) 693 | # A remark on Algorithm AS 183 694 | # Applied Statistics 34 (1985),198-200 695 | 696 | # This part is thread-unsafe: 697 | # BEGIN CRITICAL SECTION 698 | x, y, z = self._seed 699 | x = (171 * x) % 30269 700 | y = (172 * y) % 30307 701 | z = (170 * z) % 30323 702 | self._seed = x, y, z 703 | # END CRITICAL SECTION 704 | 705 | # Note: on a platform using IEEE-754 double arithmetic, this can 706 | # never return 0.0 (asserted by Tim; proof too long for a comment). 707 | return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0 708 | 709 | def getstate(self): 710 | """Return internal state; can be passed to setstate() later.""" 711 | return self.VERSION, self._seed, self.gauss_next 712 | 713 | def setstate(self, state): 714 | """Restore internal state from object returned by getstate().""" 715 | version = state[0] 716 | if version == 1: 717 | version, self._seed, self.gauss_next = state 718 | else: 719 | raise ValueError("state with version %s passed to " 720 | "Random.setstate() of version %s" % 721 | (version, self.VERSION)) 722 | 723 | def jumpahead(self, n): 724 | """Act as if n calls to random() were made, but quickly. 725 | 726 | n is an int, greater than or equal to 0. 727 | 728 | Example use: If you have 2 threads and know that each will 729 | consume no more than a million random numbers, create two Random 730 | objects r1 and r2, then do 731 | r2.setstate(r1.getstate()) 732 | r2.jumpahead(1000000) 733 | Then r1 and r2 will use guaranteed-disjoint segments of the full 734 | period. 735 | """ 736 | 737 | if not n >= 0: 738 | raise ValueError("n must be >= 0") 739 | x, y, z = self._seed 740 | x = int(x * pow(171, n, 30269)) % 30269 741 | y = int(y * pow(172, n, 30307)) % 30307 742 | z = int(z * pow(170, n, 30323)) % 30323 743 | self._seed = x, y, z 744 | 745 | def __whseed(self, x=0, y=0, z=0): 746 | """Set the Wichmann-Hill seed from (x, y, z). 747 | 748 | These must be integers in the range [0, 256). 749 | """ 750 | 751 | if not type(x) == type(y) == type(z) == int: 752 | raise TypeError('seeds must be integers') 753 | if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256): 754 | raise ValueError('seeds must be in range(0, 256)') 755 | if 0 == x == y == z: 756 | # Initialize from current time 757 | import time 758 | t = long(time.time() * 256) 759 | t = int((t&0xffffff) ^ (t>>24)) 760 | t, x = divmod(t, 256) 761 | t, y = divmod(t, 256) 762 | t, z = divmod(t, 256) 763 | # Zero is a poor seed, so substitute 1 764 | self._seed = (x or 1, y or 1, z or 1) 765 | 766 | self.gauss_next = None 767 | 768 | def whseed(self, a=None): 769 | """Seed from hashable object's hash code. 770 | 771 | None or no argument seeds from current time. It is not guaranteed 772 | that objects with distinct hash codes lead to distinct internal 773 | states. 774 | 775 | This is obsolete, provided for compatibility with the seed routine 776 | used prior to Python 2.1. Use the .seed() method instead. 777 | """ 778 | 779 | if a is None: 780 | self.__whseed() 781 | return 782 | a = hash(a) 783 | a, x = divmod(a, 256) 784 | a, y = divmod(a, 256) 785 | a, z = divmod(a, 256) 786 | x = (x + a) % 256 or 1 787 | y = (y + a) % 256 or 1 788 | z = (z + a) % 256 or 1 789 | self.__whseed(x, y, z) 790 | 791 | ## --------------- Operating System Random Source ------------------ 792 | 793 | class SystemRandom(Random): 794 | """Alternate random number generator using sources provided 795 | by the operating system (such as /dev/urandom on Unix or 796 | CryptGenRandom on Windows). 797 | 798 | Not available on all systems (see os.urandom() for details). 799 | """ 800 | 801 | def random(self): 802 | """Get the next random number in the range [0.0, 1.0).""" 803 | return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF 804 | 805 | def getrandbits(self, k): 806 | """getrandbits(k) -> x. Generates a long int with k random bits.""" 807 | if k <= 0: 808 | raise ValueError('number of bits must be greater than zero') 809 | if k != int(k): 810 | raise TypeError('number of bits should be an integer') 811 | bytes = (k + 7) // 8 # bits / 8 and rounded up 812 | x = long(_hexlify(_urandom(bytes)), 16) 813 | return x >> (bytes * 8 - k) # trim excess bits 814 | 815 | def _stub(self, *args, **kwds): 816 | "Stub method. Not used for a system random number generator." 817 | return None 818 | seed = jumpahead = _stub 819 | 820 | def _notimplemented(self, *args, **kwds): 821 | "Method should not be called for a system random number generator." 822 | raise NotImplementedError('System entropy source does not have state.') 823 | getstate = setstate = _notimplemented 824 | 825 | ## -------------------- test program -------------------- 826 | 827 | def _test_generator(n, func, args): 828 | import time 829 | print n, 'times', func.__name__ 830 | total = 0.0 831 | sqsum = 0.0 832 | smallest = 1e10 833 | largest = -1e10 834 | t0 = time.time() 835 | for i in range(n): 836 | x = func(*args) 837 | total += x 838 | sqsum = sqsum + x*x 839 | smallest = min(x, smallest) 840 | largest = max(x, largest) 841 | t1 = time.time() 842 | print round(t1-t0, 3), 'sec,', 843 | avg = total/n 844 | stddev = _sqrt(sqsum/n - avg*avg) 845 | print 'avg %g, stddev %g, min %g, max %g' % \ 846 | (avg, stddev, smallest, largest) 847 | 848 | 849 | def _test(N=2000): 850 | _test_generator(N, random, ()) 851 | _test_generator(N, normalvariate, (0.0, 1.0)) 852 | _test_generator(N, lognormvariate, (0.0, 1.0)) 853 | _test_generator(N, vonmisesvariate, (0.0, 1.0)) 854 | _test_generator(N, gammavariate, (0.01, 1.0)) 855 | _test_generator(N, gammavariate, (0.1, 1.0)) 856 | _test_generator(N, gammavariate, (0.1, 2.0)) 857 | _test_generator(N, gammavariate, (0.5, 1.0)) 858 | _test_generator(N, gammavariate, (0.9, 1.0)) 859 | _test_generator(N, gammavariate, (1.0, 1.0)) 860 | _test_generator(N, gammavariate, (2.0, 1.0)) 861 | _test_generator(N, gammavariate, (20.0, 1.0)) 862 | _test_generator(N, gammavariate, (200.0, 1.0)) 863 | _test_generator(N, gauss, (0.0, 1.0)) 864 | _test_generator(N, betavariate, (3.0, 3.0)) 865 | _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0)) 866 | 867 | # Create one instance, seeded from current time, and export its methods 868 | # as module-level functions. The functions share state across all uses 869 | #(both in the user's code and in the Python libraries), but that's fine 870 | # for most programs and is easier for the casual user than making them 871 | # instantiate their own Random() instance. 872 | 873 | _inst = Random() 874 | seed = _inst.seed 875 | random = _inst.random 876 | uniform = _inst.uniform 877 | triangular = _inst.triangular 878 | randint = _inst.randint 879 | choice = _inst.choice 880 | randrange = _inst.randrange 881 | sample = _inst.sample 882 | shuffle = _inst.shuffle 883 | normalvariate = _inst.normalvariate 884 | lognormvariate = _inst.lognormvariate 885 | expovariate = _inst.expovariate 886 | vonmisesvariate = _inst.vonmisesvariate 887 | gammavariate = _inst.gammavariate 888 | gauss = _inst.gauss 889 | betavariate = _inst.betavariate 890 | paretovariate = _inst.paretovariate 891 | weibullvariate = _inst.weibullvariate 892 | getstate = _inst.getstate 893 | setstate = _inst.setstate 894 | jumpahead = _inst.jumpahead 895 | getrandbits = _inst.getrandbits 896 | 897 | if __name__ == '__main__': 898 | _test() 899 | -------------------------------------------------------------------------------- /Programming Assignment 4/random.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/579b76e90f40056b8dea2e921e82bbd1cec4bd8d/Programming Assignment 4/random.pyc -------------------------------------------------------------------------------- /Programming Assignment 4/test.txt: -------------------------------------------------------------------------------- 1 | 1 2 3 4 7 2 | 3 | 2 1 3 4 4 | 5 | 3 1 2 4 6 | 7 | 4 1 2 3 5 8 | 9 | 5 4 6 7 8 10 | 11 | 6 5 7 8 12 | 13 | 7 1 5 6 8 14 | 15 | 8 5 6 7 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms 2 | 3 | Course can be found in [Coursera](https://www.coursera.org/learn/algorithms-divide-conquer) 4 | 5 | Quiz answers and notebook for quick search can be found in my blog [SSQ](https://ssq.github.io/2017/07/17/Coursera%20S%20Algorithms%20Specialization%20Notebook/) 6 | 7 | - Week 1 Lecture slides: 8 | - 1: Divide and Conquer: 9 | - [Integer Multiplication](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/1.2-algo1-intro2_typed.pdf); 10 | - [Karatsuba Multiplication](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/1.3-algo1-intro3_typed.pdf); 11 | - [x] [Implementation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/tree/master/Programming%20Assignment%201) by Python; 12 | - [Merge Sort](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/1.6-slides_algo-merge2_typed.pdf). 13 | - 2: Asymptotic Analysis: 14 | - [Big-oh notation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/2.2-slides_algo-asymptotic1_typed.pdf); [Omega and Theta notation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/2.4-slides_algo-asymptotic3_typed.pdf); 15 | 16 | - Week 2 Lecture slides: 17 | - 3: Divide and Conquer: 18 | - [Counting Inversions](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/3.2-slides_algo-inversions2_typed.pdf) 19 | - [x] [Implementation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/tree/master/Programming%20Assignment%202) by python; 20 | - [Matrix Multiplication](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/3.3-slides_algo-strassen_typed.pdf) Strassen’s Algorithm 21 | - [Closest Pair](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/3.4-slides_algo-closest1_typed.pdf) Optional 22 | - 4: The Master Method: 23 | - [Motivation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.1-slides_algo-master1_typed.pdf); [Example](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.3-slides_algo-master3_typed.pdf); [Proof I](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.4-slides_algo-master4_typed.pdf), [Proof II](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/4.6-slides_algo-master6_typed.pdf) 24 | 25 | - Week 3 Lecture slides: 26 | - 5: Randomized Algorithm - QuickSort: 27 | - [Overview](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.1-slides_algo-qsort-intro_typed.pdf); [The Partition Subroutine](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.2-slides_algo-qsort-partition_typed.pdf); [Proof](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.3-slides_algo-qsort-correctness_typed.pdf); [Choosing a Good Pivot](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/5.4-slides_algo-qsort-pivot_typed.pdf) 28 | - [x] [Implementation of QuickSort](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/tree/master/Programming%20Assignment%203) with 3 pivots by python 29 | - 6: QuickSort Analysis: 30 | - [the average running time of QuickSort (with random pivots)](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/6.3-slides_algo-qsort-analysis3_typed.pdf) 31 | - 7: Probability Review: 32 | 33 | - Week 4 Lecture slides: 34 | - 8: Linear-time Selection 35 | - [Randomized Selection](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/8.1-slides_algo-select-ralgorithm_typed.pdf) 36 | - [Deterministic Selection](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/8.3-slides_algo-select-dalgorithm_typed.pdf) 37 | - 9: Graphs and The Minimum Cut 38 | - [Random Contraction Algorithm](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/blob/master/Lecture%20Slides/9.3-slides_algo-karger-algorithm_typed.pdf) 39 | - [x] [Implementation](https://github.com/SSQ/Coursera-Stanford-Divide-and-Conquer-Sorting-and-Searching-and-Randomized-Algorithms/tree/master/Programming%20Assignment%204) by Python 40 | --------------------------------------------------------------------------------