python实现递归斐波那契数列、进制转换、排序

python实现递归斐波那契数列、进制转换

递归结束条件:

  1. 递归算法必须有个基本结束条件
  2. 递归算法必须改变自己的状态并向基本结束条件演进
  3. 递归算法必须递归地调用自身
def fibo(n):
    if n<=1:  #结束条件
        return n
    return fibo(n-1)+fibo(n-2)  #调用自己
print(fibo(8))



def to_str(n, base):
    convert_string = "0123456789ABCDEF"
    if n < base:
        return convert_string[n]
    else:
        return to_str(n//base, base) + convert_string[n % base]
print(to_str(1453,5))

#动态规划
def recMC(coinValueList,change):
    minCoins = change
    if change in coinValueList:
        return 1
    else:
        for i in [c for c in coinValueList if c <= change]:
            numCoins = 1 + recMC(coinValueList,change-i)
            if numCoins < minCoins:
                minCoins = numCoins
    return minCoins

print(recMC([1,5,10,25],63))

选择排序算法

def selectionSort(alist):
    for fillslot in range(len(alist)-1,0,-1):
        positionOfMax=0
        for location in range(1,fillslot+1):
            if alist[location]>alist[positionOfMax]:
                positionOfMax = location
            temp = alist[fillslot]
            alist[fillslot] = alist[positionOfMax]
            alist[positionOfMax] = temp
    return alist
alist = [54,26,93,17,77,31,44,55,20]
print(alist)
print(selectionSort(alist))

冒泡排序

def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp
alist = [54,26,99,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)

插入排序

def insertionSort(alist):
    for index in range(1,len(alist)):
        currentvalue = alist[index]
        position = index
        while position>0 and alist[position-1]>currentvalue:
            alist[position]=alist[position-1]
            position = position-1
            alist[position]=currentvalue
    return alist
alist = [54,26,93,17,77,31,44,55,20]
print(insertionSort(alist))

你可能感兴趣的:(python)