for 循环代表性经典浓缩习题

xiaoxiao2021-03-01  7

经典习题

9*9乘法打法

9*9乘法表, 并要求打印为如下图所示，倒序的乘法表，而且间距要相等 核心关键词： (1) 在如上列表中，先输出每个词组时要进行左对齐，而且要偏移左固定如3位，打印出后发现当j < 4时，需要偏移2位，才能显的整体对齐效果 #!/bin/python3 #-*- coding: UTF-8 -*- for i in range(1,10): s = '' for j in range(i,10): s += '{}*{}={:<{}}'.format(i,j,i*j,2 if j < 4 else 3) print('{:>60}'.format(s)) print()

斐波那契

#!/bin/python3 #-*- coding: UTF-8 -*- a = 0 b = 1 print(b) for i in range(1,10): a,b=b,a+b print(b)

求质素

#!/bin/python3 #-*- coding: UTF-8 -*- import datetime start = datetime.datetime.now() count = 1 for i in range(3,100001,2): if i > 10 and i%10 == 5: continue for j in range(3,int(i**0.5)+1,2): if i%j == 0: break else: count += 1 delta = (datetime.datetime.now() - start).total_seconds() print(delta) print(count) ######效率如下######### [python@centos7 323]\$./4.py 0.143254 9592

#!/bin/python3 #-*- coding: UTF-8 -*- import datetime start = datetime.datetime.now() number = 100000 count = 2 for num in range(4, number): if num%6 != 1 and num%6 != 5: continue else: snum = int(num**0.5+1) for i in range(5, snum, 2): if not num%i: break else: count += 1 pass #print(count) delta = (datetime.datetime.now() - start).total_seconds() print(delta) print(count ####效率如下###### [python@centos7 323]\$./6.py 0.14614 9592

#!/bin/python3 #-*- coding: UTF-8 -*- import math flag = False primenumber = [] for x in range(2,1000): for i in primenumber: if x % i == 0: flag = True break if i >= math.ceil(math.sqrt(x)): #最大值除以自己的开平方都不能整除的话，说明已经除到最大值， #因此就没有必要继续遍历下去，直接跳出 #等价于for i in range(x**0.5+1) break if not flag: print(x) primenumber.append(x)