Skip to content

Commit 3d9a700

Browse files
committed
code from chapter 4
1 parent 8cf108a commit 3d9a700

File tree

5 files changed

+34
-0
lines changed

5 files changed

+34
-0
lines changed

04_quicksort/python/01_loop_sum.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def sum(arr):
2+
total = 0
3+
for x in arr:
4+
total += x
5+
return total
6+
7+
print sum([1, 2, 3, 4])
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
def sum(list):
2+
if list == []:
3+
return 0
4+
return list[0] + sum(list[1:])
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
def count(list):
2+
if list == []:
3+
return 0
4+
return 1 + count(list[1:])
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def max(list):
2+
if len(list) == 2:
3+
return list[0] if list[0] > list[1] else list[1]
4+
sub_max = max(list[1:])
5+
return list[0] if list[0] > sub_max else sub_max

04_quicksort/python/05_quicksort.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
def quicksort(array):
2+
if len(array) < 2:
3+
# base case, arrays with 0 or 1 element are already "sorted"
4+
return array
5+
else:
6+
# recursive case
7+
pivot = array[0]
8+
# sub-array of all the elements less than the pivot
9+
less = [i for i in array[1:] if i <= pivot]
10+
# sub-array of all the elements greater than the pivot
11+
greater = [i for i in array[1:] if i > pivot]
12+
return quicksort(less) + [pivot] + quicksort(greater)
13+
14+
print quicksort([10, 5, 2, 3])

0 commit comments

Comments
 (0)