import random
# 大写字母的ASCII码范围
a =[chr(i)for i inrange(65,91)]# 小写字母的ASCII码范围
b =[chr(j)for j inrange(97,123)]# 数字
c =[k for k inrange(0,10)]
s =""for x inrange(1,9):# 前两位 大写字母if x <=2:
s += random.choice(a)# 3、4位 小写字母elif2< x <=4:
s += random.choice(b)# 5-8位 数字 转成字符串else:
s +=str(random.choice(c))print(s)
defanalysis(a, n):
s =""for i inrange(1, n +1):if i == n:
s +=str(a)* i
else:
s +=str(a)* i
s = s +"+"print(s)# 输出公式
result =sum([int(str(a)* i)for i inrange(1, n +1)])# 求和return result
a =int(input("输入a:"))
n =int(input("输入n:"))print("计算结果为:{}".format(analysis(a, n)))
3. 统计一段英文字符串中单词"the"的个数,并提取出首字母非t的单词。
import re
_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 =[]for i in all_str:if i in t_str:# 首字母是t的 滤掉continueelse:
no_t_str.append(i)print(no_t_str)
4. 简单实现抽奖功能
import random
rewards ={"一等奖":"汽车一辆","二等奖":"电视一台","三等奖":"洗衣液一袋"}print("一等奖---------->汽车一辆 \n二等奖---------->电视一台 \n三等奖---------->洗衣液一袋")defgetReward(rewards):
num = random.random()if0<= num <0.08:
reward ="一等奖"elif0.08<= num <0.3:
reward ="二等奖"elif0.3<= num <1:
reward ="三等奖"# 返回对应奖项和奖项对应的值return reward, rewards[reward]for i inrange(3):
order =input("按回车键抽奖...")
k, v = getReward(rewards)print("第{}次抽奖结果:{}---->{}".format(i +1, k, v))
5. 编写函数,接收一个任意字符串,返回其中最长的连续数字子串。
import re
deflongest_num(s):# 匹配多个数字 返回一个列表
nums = re.findall(r'\d+', s)
_nums =[int(i)for i in nums]returnmax(_nums)# 最长的# 举例输入# 123 python36a12345snfsig1?!132975..# abcd12345ed125ss123456789
string =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)for m inrange(length -1):
flag =Truefor n inrange(length - m -1):if nums[n]> nums[n+1]:
nums[n], nums[n+1]= nums[n+1], nums[n]
flag =Falseif flag:breakprint("排序后:{}".format(nums))