code from chapter 4

This commit is contained in:
Aditya Bhargava
2016-03-02 14:29:05 -08:00
parent 8cf108a20c
commit 3d9a7000c7
5 changed files with 34 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
def sum(arr):
total = 0
for x in arr:
total += x
return total
print sum([1, 2, 3, 4])

View File

@@ -0,0 +1,4 @@
def sum(list):
if list == []:
return 0
return list[0] + sum(list[1:])

View File

@@ -0,0 +1,4 @@
def count(list):
if list == []:
return 0
return 1 + count(list[1:])

View File

@@ -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

View File

@@ -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])