From 3d9a7000c77f9d2a26a976bb8dc2cacdd1975a6e Mon Sep 17 00:00:00 2001 From: Aditya Bhargava Date: Wed, 2 Mar 2016 14:29:05 -0800 Subject: [PATCH] code from chapter 4 --- 04_quicksort/python/01_loop_sum.py | 7 +++++++ 04_quicksort/python/02_recursive_sum.py | 4 ++++ 04_quicksort/python/03_recursive_count.py | 4 ++++ 04_quicksort/python/04_recursive_max.py | 5 +++++ 04_quicksort/python/05_quicksort.py | 14 ++++++++++++++ 5 files changed, 34 insertions(+) create mode 100644 04_quicksort/python/01_loop_sum.py create mode 100644 04_quicksort/python/02_recursive_sum.py create mode 100644 04_quicksort/python/03_recursive_count.py create mode 100644 04_quicksort/python/04_recursive_max.py create mode 100644 04_quicksort/python/05_quicksort.py diff --git a/04_quicksort/python/01_loop_sum.py b/04_quicksort/python/01_loop_sum.py new file mode 100644 index 0000000..b43c5e3 --- /dev/null +++ b/04_quicksort/python/01_loop_sum.py @@ -0,0 +1,7 @@ +def sum(arr): + total = 0 + for x in arr: + total += x + return total + +print sum([1, 2, 3, 4]) diff --git a/04_quicksort/python/02_recursive_sum.py b/04_quicksort/python/02_recursive_sum.py new file mode 100644 index 0000000..bf3a358 --- /dev/null +++ b/04_quicksort/python/02_recursive_sum.py @@ -0,0 +1,4 @@ +def sum(list): + if list == []: + return 0 + return list[0] + sum(list[1:]) diff --git a/04_quicksort/python/03_recursive_count.py b/04_quicksort/python/03_recursive_count.py new file mode 100644 index 0000000..c83630a --- /dev/null +++ b/04_quicksort/python/03_recursive_count.py @@ -0,0 +1,4 @@ +def count(list): + if list == []: + return 0 + return 1 + count(list[1:]) diff --git a/04_quicksort/python/04_recursive_max.py b/04_quicksort/python/04_recursive_max.py new file mode 100644 index 0000000..c32fb54 --- /dev/null +++ b/04_quicksort/python/04_recursive_max.py @@ -0,0 +1,5 @@ +def max(list): + if len(list) == 2: + return list[0] if list[0] > list[1] else list[1] + sub_max = max(list[1:]) + return list[0] if list[0] > sub_max else sub_max diff --git a/04_quicksort/python/05_quicksort.py b/04_quicksort/python/05_quicksort.py new file mode 100644 index 0000000..bb98746 --- /dev/null +++ b/04_quicksort/python/05_quicksort.py @@ -0,0 +1,14 @@ +def quicksort(array): + if len(array) < 2: + # base case, arrays with 0 or 1 element are already "sorted" + return array + else: + # recursive case + pivot = array[0] + # sub-array of all the elements less than the pivot + less = [i for i in array[1:] if i <= pivot] + # sub-array of all the elements greater than the pivot + greater = [i for i in array[1:] if i > pivot] + return quicksort(less) + [pivot] + quicksort(greater) + +print quicksort([10, 5, 2, 3])