猫史档案馆


【Python作品分享】算法2

用户:芙兰朵露_斯卡雷特芙兰朵露_斯卡雷特查看:0 回复:0 评论:0 创建时间:2021-01-22T20:19:18


【作品展示】

center_image

 

【作品介绍】

介绍递归

 

【作品源代码】

#算法3:递归
#用循环来找箱子堆里的钥匙。
def look_for_key(main_box):
    pile = main_box.make_a_pile_to_look_through()
    while pile is not empty:
        box = pile.grab_a_box()
        for item in box:
            if item.is_a_box:
                pile.append(item)
            elif item.is_a_key():
                print("found the key!")


#第二种方法,效果不变。
def look_for_key2(box2):
    for item in box2:
        if item.is_a_box2():
            look_for_key2(item)
        elif item.is_a_key():
            print("found the key!")


#另一个函数,用基线条件和递归条件
def countdown(i):
    print(i)
    if i <= 0: #基线条件
        return
    else: #递归条件
        countdown(i-1)


#下面两个函数为一体,使用栈来运行。
def greet(name):
    print("Hello, " + name + "!")
    geeet2(name)
    print("getting reaby to say bye...")
    bye()


def greet2(name):
    print("how are you, " + name + "?")
    def bye():
       print("ok bye!")


#递归调用栈
def fact(x):
    if x == 1:
        return 1
    else:
        return x * fact(x-1)


#算法4:快速排序D&C
#循环解决数组
def sum(arr):
    total = 0
    for x in arr:
        total += x
    return total


print(sum([1, 2, 3, 4]))


#递归解决数组
def sum(list):
    if list == []:
        return 0
    return list[0] + sum(lit[1:])


#用递归来计算列表包含的元素数
def count(list):
    if list == []:
        return 0
    return 1 + count(list[1:])


#用递归找出列表最大的数
def max(list):
    if len(list) == 2:
        return
    sub_max = max(list[1:])
    return list[0] if list[0] > sub_max else sub_max


#用递归排序数组
def quicksort(array):
    i = 1
    if len(array) < 2:
        return array
    else:
        pivot = array[0]
        iess = [i for i in array[i:] if i <= pivot]


        greater = [i for i in array[i:] if i > pivot]


        return quicksort(iess) + [pivot] + quicksort(greater)


print(quicksort([10, 5, 2, 3]))


#用递归打印简单函数
def print_items(list):
    for item in list:
        time.sleep(1)
        print(item)













 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 0下一页