1. 冒泡排序
def bubble_sort(lists): len_list=len(lists) for i in range(len_list): for j in range(len_list-i-1): if lists[j]>lists[j+1]: lists[j],lists[j+1]=lists[j+1],lists[j] print(lists) return lists
2. 插入排序
def insert_sort(lists): for i in range(len(lists)): position=i while position>0: if lists[position]<lists[position-1]: lists[position],lists[position-1]=lists[position-1],lists[position] position-=1 print(lists) return lists
3. 列表去重
#第一种方式 s=[1,2,6,3,1,5,2] list(set(s))
#第二种方式 l=[1,1,6,3,1,5,2] def duplictae(lists): L=[] for i in lists: if i not in L: L.append(i) return L print(duplictae(l))
4.字符串反转,例如:将string反转输出为:gnirts
#第一种方式: def str_reverse(str): return str[::-1]
#第二种方式: def str_reverse(str): L=list(str) L.reverse() new_str=\'\'.join(L) return new_str
5.快速交换两个变量值的方法
# 方法一:通过新添加中间变量的方式,交换数值. def test(a,b): c=a a=b b=c print(a,b)
# 方法二:(此方法是Python中特有的方法) # 直接将a,b两个变量放到元组中,再通过元组按照index进行赋值的方式进行重新赋值给两个变量 def test(a,b): a,b=b,a print(a,b)
# 方法三:通过简单的逻辑运算进行将两个值进行互换 def test(a,b): a=a+b b=a-b a=a-b print(a,b) res = test(50,100)
6.删除字符串中的特殊字符,并输出指定字符串
如:str = \'welcome to shui&di\',指定输出:shuidi
str = \'welcome to shui&di\' new_str=str.split(\' \')[2].split(\'&\') res = \'\'.join(new_str)
7.在1-100之间生成一个随机数,并猜所生成的随机数值,根据猜的结果,给出正确、太大、太小的提示,如果5次均未猜对,游戏结束!
num = random.randint(1,100) for i in range(5): new_num = int(input(\'请输入猜测数值:\')) if new_num > num: print(\'太大了\') elif new_num < num: print(\'太小了\') elif new_num == num: print(\'猜对了!\') else: print(\'游戏结束!\')
8.把字符串\'ssysyysy\'变成\'ssssyyyy\'
1 a= \'ssysyysy\' 2 a_s = a.split(\'y\') 3 s = \'\'.join(a_s) 4 5 a_y = a.split(\'s\') 6 y = \'\'.join(a_y) 7 8 print(s+y)