1. 随机生成由2个大写字母(前2位)+2个小写字母(第3、4位)+4个数字(第5-8位)组成的密码(字符串)
importrandom# 大写字母的ASCII码范围a= [chr(i) foriinrange(65, 91)] # 小写字母的ASCII码范围b= [chr(j) forjinrange(97, 123)] # 数字c= [kforkinrange(0, 10)] s=""forxinrange(1, 9): # 前两位 大写字母ifx<=2: s+=random.choice(a) # 3、4位 小写字母elif2<x<=4: s+=random.choice(b) # 5-8位 数字 转成字符串else: s+=str(random.choice(c)) print(s)
2. 编写函数,输出公式a+aa+aaa+…并计算其结果,其中a为1-9之间的整数,公式的项为n,如a和n分别为3和5时,输出并计算公式 3+33+333+3333+33333。
defanalysis(a, n): s=""foriinrange(1, n+1): ifi==n: s+=str(a) *ielse: s+=str(a) *is=s+"+"print(s) # 输出公式result=sum([int(str(a) *i) foriinrange(1, n+1)]) # 求和returnresulta=int(input("输入a:")) n=int(input("输入n:")) print("计算结果为:{}".format(analysis(a, n)))
3. 统计一段英文字符串中单词"the"的个数,并提取出首字母非t的单词。
importre_str='It was this sense of freedom the first innovation entrusted by the west life to the Individualism.' \ ' On the other hand, American pioneers lost their comfortable life when they were trying to break ' \ 'away from the fetters of the old social order caused by the civilized society. Hence, they had to ' \ 'live by themselves with their independent spirit of pioneering .'the_count=_str.count("the") # "the" 的个数print("单词the的个数:{}".format(the_count)) # 提取英文单词 "\b"表示单词的开头或结尾 返回列表t_str=re.findall(r'\bt[a-zA-Z]+\b', _str) all_str=re.findall(r'\b[a-zA-Z]+\b', _str) print(all_str) # 所有单词print(t_str) # 首字母含t的no_t_str= [] foriinall_str: ifiint_str: # 首字母是t的 滤掉continueelse: no_t_str.append(i) print(no_t_str)
4. 简单实现抽奖功能
importrandomrewards={"一等奖": "汽车一辆", "二等奖": "电视一台", "三等奖": "洗衣液一袋"} print("一等奖---------->汽车一辆 \n二等奖---------->电视一台 \n三等奖---------->洗衣液一袋") defgetReward(rewards): num=random.random() if0<=num<0.08: reward="一等奖"elif0.08<=num<0.3: reward="二等奖"elif0.3<=num<1: reward="三等奖"# 返回对应奖项和奖项对应的值returnreward, rewards[reward] foriinrange(3): order=input("按回车键抽奖...") k, v=getReward(rewards) print("第{}次抽奖结果:{}---->{}".format(i+1, k, v))
5. 编写函数,接收一个任意字符串,返回其中最长的连续数字子串。
importredeflongest_num(s): # 匹配多个数字 返回一个列表nums=re.findall(r'\d+', s) _nums= [int(i) foriinnums] returnmax(_nums) # 最长的# 举例输入# 123 python36a12345snfsig1?!132975..# abcd12345ed125ss123456789string=input("输入字符串为:") result=longest_num(string) print("最长的连续数字子串为:{}".format(str(result)))
6. 冒泡排序
nums= [1, 9, 8, 5, 6, 7, 4, 3, 2] print("排序前:{}".format(nums)) length=len(nums) forminrange(length-1): flag=Trueforninrange(length-m-1): ifnums[n] >nums[n+1]: nums[n], nums[n+1] =nums[n+1], nums[n] flag=Falseifflag: breakprint("排序后:{}".format(nums))