Calvin (Deutschbein)
W15Mon: 02 Dec
def add_peanut(peanut, peanuts:list)->list:
index = 0 # we'll look at peanuts in order
while peanut < peanuts[index]: # see if our peanut's taller
index += 1 # if it is, we keep going
return peanuts[:index] + peanut + peanuts[:index]
def order_peanuts(peanuts:list)->list:
ordered = [peanuts[0]]
for peanut in peanuts[1:]:
index = 0
while index < len(ordered) and peanut > ordered[index]:
index += 1
ordered.insert(index, peanut)
return ordered
|
def order_peanuts(peanuts:list)->list:
|
|
def order_peanuts(peanuts:list)->list:
half = len(peanuts) // 2
head = peanuts[:half]
tail = peanuts[half:]
|
|
def order_peanuts(peanuts:list)->list:
half = len(peanuts) // 2
head = peanuts[:half]
tail = peanuts[half:]
head = order_peanuts(head)
tail = order_peanuts(tail)
|
|
def order_peanuts(peanuts:list)->list:
half = len(peanuts) // 2
head = peanuts[:half]
tail = peanuts[half:]
head = order_peanuts(head)
tail = order_peanuts(tail)
return merge(head,tail)
|
|
def order_peanuts(peanuts:list)->list:
if len(peanuts) < 2:
return peanuts
half = len(peanuts) // 2
head = peanuts[:half]
tail = peanuts[half:]
head = order_peanuts(head)
tail = order_peanuts(tail)
return merge(head,tail)
|
We need to write "merge"
We can merge like so:
|
We can sort like so:
|
compares = [0,0]
def merge_peanuts(head, tail):
merged = []
while head and tail:
compares[0] += 1 # NEW !!!
if head[0] < tail[0]:
index = 0
while index < len(ordered) and peanut > ordered[index]:
compares[1] += 1 # NEW !!!
index += 1
from random import randint
peanuts = [randint(0,1000000) for _ in range(10000)]
compares = [0,0]
order_peanuts_merge(peanuts)
order_peanuts_oneat(peanuts)
print(compares)
[120410, 25412110]
def merge_peanuts(head, tail):
merged = []
while head and tail:
compares[0] += 1
if head[0] < tail[0]:
merged += [head[0]]
head = head[1:]
else:
merged += [tail[0]]
tail = tail[1:]
merged += head + tail
return merged
def order_peanuts(peanuts):
if len(peanuts) < 2:
return peanuts
half = len(peanuts) // 2
head = peanuts[:half]
tail = peanuts[half:]
head = order_peanuts(head)
tail = order_peanuts(tail)
return merge(head,tail)
merge = merge_peanuts
order_peanuts_merge = order_peanuts
def order_peanuts_oneat(peanuts:list)->list:
ordered = [peanuts[0]]
for peanut in peanuts[1:]:
index = 0
while index < len(ordered) and peanut > ordered[index]:
compares[1] += 1
index += 1
ordered.insert(index, peanut)
return ordered
from random import randint
peanuts = [randint(0,1000000) for _ in range(10000)]
compares = [0,0]
order_peanuts_merge(peanuts)
order_peanuts_oneat(peanuts)
print(compares)