美文网首页
(深坑)问题收集

(深坑)问题收集

作者: AllenDown | 来源:发表于2018-03-10 21:35 被阅读0次

    1.斐波那契数列问题

    • 定义:

    f(1) = 1;
    f(2) = 1;
    f(n) = f(n-1) + f(n-2);

    • 代码:
    # 方法一:递归实现,这种实现方式当n很大时,会有栈溢出问题,内存占用大
    def fib(n):
        if n == 1 or n == 2:
            return 1;
        else:
            return fib(n-1) + fib(n-2);
    
    # 方法二:循环实现
    def fib(n):
        if n == 1 or n == 2:
            return 1;
        i, first, second = 2, 0, 1;
        while i <= n:
            first, second = second, first + second;
            i = i+1;
        return second;
    

    2.反转单词

    例:
    "how are you" -> "you are how"

    # 方法一:将字符串分割成全部单词组成的列表,再利用切片
    # 由后向前遍历,用空格连接每个单词,组成新的字符串并返回;
    def reverse_words(s):
        return " ".join(s.split()[::-1])
    
    
    # 方法二:先反转整个字符串,再反转每个单词
    def reverse_words2(s):
        # 整个字符串整体反转
        # how are you -> uoy era woh
        list = s[::-1].split()
        # 对每一个元素进行反转
        # uoy era woh -> you are how
        list2 = [i[::-1] for i in list]
        return " ".join(list2)
    
    

    3.快速排序

    def quick_sort(list, first, last):
        if first >= last:
            return;
        key = list[first];
        i, j = first, last;
        while j > i:
            while j > i:
                if list[j] >= key:
                    j = j - 1;
                else:
                    break;
            if j > i:
                list[i],list[j] = list[j], key;
            while j > i:
                if list[i] <= key:
                    i = i + 1;
                else:
                    break;
            if j > i:
                list[i],list[j] = key, list[i];
        quick_sort(list, first, i-1);
        quick_sort(list, i+1, last);
    

    相关文章

      网友评论

          本文标题:(深坑)问题收集

          本文链接:https://www.haomeiwen.com/subject/dugbfftx.html