1、求10万内的所有素数 import datetime start=datetime.datetime.now() import math primenumber = [2] flag = False for i in range(3,100000,2): if i > 10 and i % 10 == 5: continue edge = math.ceil(math.sqrt(i)) for j in primenumber: if i % j == 0 : flag = True break if j >= edge: flag = False break if not flag: print(i) primenumber.append(i) delta = (datetime.datetime.now() - start).total_seconds() #时间计算 print(delta)
2、计算杨辉三角前6行 (1)方法1:补头和尾,中间循环 triangle = [[1],[1,1]] n = 6 for i in range(2,n): newline = [1] pre = trangle[i-1] for j in range(i-1): val = pre[j] + pre[j+1] newline.append(val) newline.append(1) trangle.append(newline) print(trangle)
(2)方法1变体 n = 6 for i in range(n): #如果不想每次判断,则把[1]放在循环外边 newline = [1] if i == 0: print(newline) continue for j in range(i-1): val = pre[j] + pre[j+1] newline.append(val) newline.append(1) print(newline) pre = newline
(3)方法2:尾部补0法 n = 6 for i in range(1,n): if i == 0: newline = [1] print(newline) newline.append(0) oldline = newline continue newline = [] for j in range(i+1): newline.append(oldline[j-1] + oldline[j]) print(newline) newline.append(0) oldline = newline
(4)方法2变体:尾部补0法 n = 6 newline = [1] print(newline) newline.append(0) for i in range(1,n): newline = [] for j in range(i+1): newline.append(oldline[j-1] + oldline[j]) print(newline) newline.append(0) oldline = newline
(5)方法3:一次性开辟空间,再对称。 n = 6 triangle = [] for i in range(n): row = [1] * (i+1) #一次性开辟 triangle.append(row) for j in range(1,i//2+1): # i=2,第三行才能进来 val = triangle[i-1][j-1] + triangle[i-1][j] row[j] = val if i != 2*j: #奇数个数的中点跳过 row[-j-1] = val print(triangle)
(6)方法4:单行覆盖 n = 6 row = [1] * n #一次性开辟足够的空间 for i in range(n): offset = n - i z = 1 #因为会有覆盖影响计算,所以引入一个临时变量 for j in range(1,i//2+1): val = z + row[j] row[j],z = val,row[j] if i != 2*j: row[-j-offset] = val print(row[:i+1])
3、依次接收用户输入的3个数,排序后打印 (1)分支结构 nums = [] out = None for i in range(3): nums.append(int(input('{}: '.format(i)))) if nums[0]>nums[1]: if nums[1]>nums[2]: out = [0,1,2] elif nums[0]>nums[2]: out = [0,2,1] else: out = [2,0,1] elif nums[0]>nums[2]: out = [1,0,2] elif nums[1]>nums[2]: out = [1,2,0] else: out = [2,1,0] out.reverse() for i in out: print(nums[i],end=',')
(2)max函数 nums = [] out = None for i in range(3): nums.append(int(input('{}: '.format(i)))) #此处不能使用for循环,不能一边迭代该列表,同时删除或者增加该列表 while True: cur = max(nums) print(cur) nums.remove(cur) if len(nums) == 1: print(nums[0]) break
(3)列表sort实现 nums = [] for i in range(3): nums.append(int(input('{}: '.format(i)))) nums.sort() print(nums)
4、经典冒泡法。 (1)初始实现 lst = [9,5,1,2,6] length = len(lst) for i in range(length): for j in range(length-1-i): if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] print(lst)
(2)优化实现 lst = [9,5,1,2,6] length = len(lst) for i in range(length): flag = False for j in range(length-1-i): if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] flag = True if not flag: break print(lst)