11、获取今天的日期
# 获取今天的日期
import datetime
today = datetime.date.today()
print(today)
12、冒泡程序
print('{:-^30}'.format('这是一个从小到大排序的冒泡程序,从大到小同理'))
lst = [34,11,7,87,446,78,95,12,6,65,44,28]
for i in range(len(lst)-1):
for j in range(len(lst)-1-i):
if lst[j] > lst[j+1]:
lst[j],lst[j+1] = lst[j+1],lst[j]
print(lst)
13、字符串判断
string = 'hello,my name is 123@,nice to meet you, 456!'
count_alpha = 0
count_digit = 0
count_space = 0
count_others = 0
for c in string:
if c.isalpha():
count_alpha += 1
elif c.isdigit():
count_digit += 1
elif c.isspace():
count_space += 1
else:
count_others += 1
print(f'count_alpha:{count_alpha}')
print(f'count_digit:{count_digit}')
print(f'count_space:{count_space}')
print(f'count_others:{count_others}')
14、实现平方根计算
# 实现计算平方根
print('{:-^30}'.format('第一种方法'))
import math
print(math.sqrt(10)) # 平方根的英文缩写为square root
print('{:-^30}'.format('第二种方法'))
def square_root(item,dot=None) ->float:
"""
:param item:需要求平方根的值
:param dot: 以四舍五入方式保留小数点后几位,默认值为None,即全部
:return: 平方根结果
"""
root = item**0.5
if dot:
if not isinstance(dot,int):
raise TypeError('dot 应传入整数参数')
return round(root,dot)
else:return root
print(square_root(10))
15、斐波那契数列
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
for i in range(10):
print(fib(i))
16、获取最大值
print('{:-^30}'.format('第一种方法'))
lst = [33,2,43,46,87,19,54,777,32,59,8,246]
print(max(lst))
print('{:-^30}'.format('第二种方法'))
lst.sort() # 升序排序
print(lst[-1])
print('{:-^30}'.format('第三种方法'))
lst.sort(reverse=True) #降序排序
print(lst[0])
17、计算最大公约数
def hcf(x,y):
smaller = x if x<y else y
for i in range(1,smaller+1):
if x%i==0 and y%i==0:
max_hcf = i
else:
pass
return max_hcf
print(hcf(15,70))
18、计算最小公倍数
def gbs(x,y):
bigger = x if x>y else y
for i in range(x,x*y+1):
if i%x==0 and i%y==0:
min_gbs = i
break
return min_gbs
print(gbs(15,20))
19、计算阶乘n!
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(4))
20、两种生成随机验证码的方式
print('{:-^40}'.format('第一种方法'))
import random
l = []
for i in range(65,91):
l.append(chr(i))
for j in range(97,123):
l.append(chr(j))
for k in range(48,58):
l.append(chr(k))
print(','.join(random.sample(l,4)))
print('{:-^40}'.format('第二种方法(导入string库更方便)'))
import random
import string
id = ','.join(random.sample(string.digits + string.ascii_letters,4))
print(id)
|