Prg2/recur practice

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา

mylen (example)

def mylen(lst):
    if lst == []:
        return 0
    else:
        return 1 + mylen(lst[1:])

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 []