常见题目

求n以内的质数(素数)

from math import sqrt


def fun(n):
li = []
for i in range(2, n + 1):
count = 0
for j in range(2, int(sqrt(i) + 1)):
'''
不用除到n是因为:
假如一个数N是合数,它有一个约数a,那么有a×b=N
则a、b两个数中必有一个大于或等于根号N,一个小于或等于根号N。
因此,只要小于或等于根号N的数(1除外)不能整除N,则N一定是素数
'''
if i % j == 0:
count += 1
if count == 0:
li.append(i)
return li


def fun2(n):
'''
5及以上的自然数可以表示为 6x+5 6x 6x +1 6x+2 6x+3 6x+4 其中只有6x+5和6x+1 不被2,3整除,所以有以下:
'''
li = [2, 3]
for i in range(5, n + 1):
if i % 6 == 1 or i % 6 == 5:
li.append(i)

return li


print(fun(100))

print(fun(5))

单链表反转

class Node(object):
    def __init__(self, elem, next_=None):
        self.elem = elem
        self.next = next_
 
def reverseList(head):
    if head == None or head.next==None:  # 若链表为空或者仅一个数就直接返回
        return head 
    pre = None
    next = None
    while(head != None): 
        next = head.next     # 1
        head.next = pre     # 2
        pre = head      # 3
        head = next      # 4
    return pre

if __name__ == '__main__':
    l1 = Node(3)    # 建立链表3->2->1->9->None
    l1.next = Node(2)
    l1.next.next = Node(1)
    l1.next.next.next = Node(9)
    l = reverseList(l1)
    print (l.elem, l.next.elem, l.next.next.elem, l.next.next.next.elem)

更多可参考:https://blog.csdn.net/gongliming_/article/details/88712221

快速排序

def quick_sort(q_list: list) -> list:
    if len(q_list) == 0:
        return []
    q_list_first = q_list[0]
    q_list_less = quick_sort([i for i in q_list[1:] if i < q_list_first])
    q_list_more = quick_sort([i for i in q_list[1:] if i >= q_list_first])
    return q_list_less + [q_list_first] + q_list_more

青蛙跳台

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法?

假设跳n阶台阶有f(n)种方法,就有两种情况,第一次跳了1阶,剩下n-1阶有f(n-1)种跳法;第一次跳了2阶,剩下的n-2阶有f(n-2)种跳法,那么总共的跳法数就是f(n-1)+f(n-2)。

那么就是相当于求斐波那契数列第n个值,初始两个值为1,1

假如一次跳的阶数可以是1到n

那么第一阶数就有f(n-1)+f(n-2)...+1=f(n)

那么f(n)=2f(n-1)

所以有2**(n-1)种跳法

 
原文地址:https://www.cnblogs.com/ycg-blog/p/12793482.html