Prg2/recur practice
รุ่นแก้ไขเมื่อ 08:07, 28 กุมภาพันธ์ 2562 โดย Jittat (คุย | มีส่วนร่วม)
เนื้อหา
mysort (example)
def insert_sorted(s, x):
if s == []:
return [x]
y = s[0]
if x <= y:
return [x] + s
else:
return [y] + insert_sorted(s[1:], x)
def mysort(lst):
if lst == []:
return lst
x = lst[-1]
del lst[-1]
s = mysort(lst)
return insert_sorted(s, x)
from random import shuffle
t = list(range(50000))
shuffle(t)
print(mysort(t))
mysum
def mysum(lst):
"""
>>> mysum([])
0
>>> mysum([10])
10
>>> mysum([10, 20, 30])
60
>>> mysum([1,0,-10,5,9])
5
"""
return 0
To test, call
python -m doctest mysum.py
mymax
def mymax(lst):
"""
>>> mymax([1])
1
>>> mymax([-10, -30, -50])
-10
>>> mymax([1, 2, 3, -10])
3
>>> mymax([5000,6,7,100,2])
5000
>>> mymax([5,6,7,100,2])
100
>>> mymax([5,6,7,100,200])
200
"""
return 0
mymerge
def mymerge(lst1, lst2):
"""
>>> mymerge([1,2,3],[])
[1, 2, 3]
>>> mymerge([],[4,5,6])
[4, 5, 6]
>>> mymerge([1,2,5,6,10],[2,3,4,5,8,9,12])
[1, 2, 2, 3, 4, 5, 5, 6, 8, 9, 10, 12]
>>> mymerge([6],[2,3,4,5,8,9,12])
[2, 3, 4, 5, 6, 8, 9, 12]
>>> mymerge([2,3,4,5,8,9,12],[7])
[2, 3, 4, 5, 7, 8, 9, 12]
"""
return []