当前位置: 首页 > wzjs >正文

泾川县建设局网站免费标志在线设计

泾川县建设局网站,免费标志在线设计,yole市场调研公司,银川做网站的 公司有哪些第21节课 【集合与字典编程练习题】 练习01 密码强度检测 在设计密码强度检测系统时,需要检查密码是否包含不同类型的字符,如大写字母、小写字母、数字和特殊字符。 给定一个密码字符串 password,编写一个函数,使用集合来检查密码…

第21节课 【集合与字典编程练习题】

练习01 密码强度检测

在设计密码强度检测系统时,需要检查密码是否包含不同类型的字符,如大写字母、小写字母、数字和特殊字符。

给定一个密码字符串 password,编写一个函数,使用集合来检查密码中是否同时包含大写字母、小写字母、数字和特殊字符(假设特殊字符为 !@#$%^&*)。如果包含所有类型的字符,返回 True,否则返回 False

# 思路1
# 用字典给每一个类型做计数
# def check(password):
#     pw_dic = {"upper":0, "lower":0, "number":0, "special":0}
#     for letter in password:
#         if letter.islower():
#             pw_dic["lower"] += 1
#         elif letter.isupper():
#             pw_dic['upper'] += 1
#         elif letter.isdigit():
#             pw_dic['number'] += 1
#         elif letter in "!@#$%^&*":
#             pw_dic['special'] += 1
#         else:
#             return False
#     for value in pw_dic.values():
#         if value == 0:
#             return False
#     return True# 思路2
def check(password):password = set(password)upper = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")lower = set()for i in range(26):lower.add(chr(97 + i))number = set('0123456789')special = set('!@#$%^&*')if len(password - (upper | lower | number | special)) > 0:return Falsereturn len(password & upper) > 0 and len(password & lower) > 0 and len(password & number) > 0 and len(password & special) > 0password = input()
print(check(password))

练习02 统计关键字的个数

创建一个字符串变量,内容为某一篇Python源代码,用re.findall(r'\b[a-zA-Z]+\b', sources)解析出所有的英文单词,统计关键字的个数。

sources = """
BEGIN_YEAR = 2000
BEGIN_MONTH = 1
BEGIN_WEEK = 6
def get_month_str(month):if month == 1:return "一月"elif month == 2:return "二月"elif month == 3:return "三月"elif month == 4:return "四月"elif month == 5:return "五月"elif month == 6:return "六月"elif month == 7:return "七月"elif month == 8:return "八月"elif month == 9:return "九月"elif month == 10:return "十月"elif month == 11:return "十一月"elif month == 12:return "十二月"
def print_month_title(month):print("          ", get_month_str(month))print(" ---------------------------")print("  一  二  三  四  五  六  日")print()
def is_leapyear(year):return 400 % year == 0 or (year % 4 == 0 and year % 100 != 0)
def get_days_count(year, month):if month in [1, 3, 5, 7, 8, 10, 12]:return 31elif month in [4, 6, 9, 11]:return 30elif is_leapyear(year):return 29else:return 28
def get_days_begin(year, month):total_days = 0for i in range(BEGIN_YEAR, year):if is_leapyear(i):total_days += 366else:total_days += 365for i in range(BEGIN_MONTH, month):total_days += get_days_count(year, i)return (total_days % 7 + BEGIN_WEEK) % 7
def print_month_body(year, month):days_count = get_days_count(year, month)days_begin = get_days_begin(year, month)cur_count = 0for i in range(days_begin):print("    ", end="")cur_count += 1for i in range(1, days_count + 1):print("%4d" % i, end="")cur_count += 1if cur_count % 7 == 0:print()print()
def print_month(year, month):print_month_title(month)print_month_body(year, month)
def print_calendar(year):for month in range(1, 13):print_month(year, month)
if __name__ == "__main__":year = int(input("请输入年份(2000年起步):"))print_calendar(year)
"""
import re
import keyword
kwords = keyword.kwlist
words = re.findall(r'\b[a-zA-Z]+\b', sources)
# print(words)
# print(kwords)d = dict()
for word in words:if word in kwords:if word in d:d[word] += 1else:d[word] = 1
print(d)

练习03 统计单词的个数

创建一个字符串变量,内容为某一篇英文文章,用re.findall(r'\b[a-zA-Z]+\b', sources)解析出所有的英文单词,统计每个英文单词出现的次数。

sources = """
# The Magic of ReadingReading is a magical journey that transports us to different worlds, times, and perspectives. With a book in hand, we can explore ancient civilizations, visit far - off galaxies, or delve into the human psyche.One of the greatest benefits of reading is its ability to expand our knowledge. Whether it's a history book, a science manual, or a work of fiction, each page offers new information, ideas, and vocabulary. It also enhances our imagination. When we read, we create vivid images in our minds, which enriches our creativity.Moreover, reading is a great way to relax. In a world full of stress and distractions, getting lost in a good book allows us to unwind and recharge. It can reduce anxiety and improve our overall well - being.In conclusion, reading is not just an activity; it's a lifelong companion that educates, inspires, and soothes us. So, pick up a book today and start your own magical adventure. 
"""
import re
words = re.findall(r'\b[a-zA-Z]+\b', sources)
print(words)
d = dict()
for word in words:lower_wd = word.lower()if lower_wd in d:d[lower_wd] += 1else:d[lower_wd] = 1for key in d.keys():print(key, " = ", d[key])

练习04 升序显示不重复的单词

创建一个字符串变量,内容为某一篇英文文章,用re.findall(r'\b[a-zA-Z]+\b', sources)解析出所有的英文单词,按升序显示所有不重复的单词。

sources = """
# The Magic of ReadingReading is a magical journey that transports us to different worlds, times, and perspectives. With a book in hand, we can explore ancient civilizations, visit far - off galaxies, or delve into the human psyche.One of the greatest benefits of reading is its ability to expand our knowledge. Whether it's a history book, a science manual, or a work of fiction, each page offers new information, ideas, and vocabulary. It also enhances our imagination. When we read, we create vivid images in our minds, which enriches our creativity.Moreover, reading is a great way to relax. In a world full of stress and distractions, getting lost in a good book allows us to unwind and recharge. It can reduce anxiety and improve our overall well - being.In conclusion, reading is not just an activity; it's a lifelong companion that educates, inspires, and soothes us. So, pick up a book today and start your own magical adventure. 
"""
import re
words = re.findall(r'\b[a-zA-Z]+\b', sources)
words = [word.lower() for word in words]
lst = list(set(words))
lst.sort()
print(lst)

练习05 唯一摩尔斯密码词

题目描述

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如:

  • ‘a’ 对应 ".-"
  • ‘b’ 对应 "-..."
  • ‘c’ 对应 "-.-."以此类推

为了方便,所有26个英文字母的摩尔斯密码表如下:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

给你一个字符串数组 words ,每个单词可以写成每个字母对应摩尔斯密码的组合。

例如,“cab” 可以写成 "-.-..--..." ,(即 "-.-." + ".-" + "-..." 字符串的结合)。我们将这样一个连接过程称作 单词翻译

对 words 中所有单词进行单词翻译,返回不同 单词翻译 的数量

输入输出描述

输入一组单词

输出不一样的翻译数量

示例

输入:

gin zen gig msg

输出:

2

解释:

各单词翻译如下:
“gin” -> “–…-.”
“zen” -> “–…-.”
“gig” -> “–…–.”
“msg” -> “–…–.”

共有 2 种不同翻译, “–…-.” 和 “–…–.”.

morses = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]def sovle(words):st = set()for word in words:pwd = ""for letter in word:pwd += morses[ord(letter) - 97]st.add(pwd)return len(st)
words = input().split(" ")
print(sovle(words))

练习06 前K个高频元素

题目描述

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

输入输出描述

输入数组长度n和k,接下来输入n个元素

输出前k个高频元素

示例

输入:

6 2

1 1 1 2 2 3

输出:

1 2

# 思路1 用字典计数 key=数字 value=次数,对values进行排序
"""
arr = [1,3,1,2,1,2,1,4,1,3,2,2,3,1,1,4,2]
k = 3
dic = dict()
for num in arr:if num in dic:dic[num] += 1else:dic[num] = 1keys_lst = list(dic.keys())
values_lst = list(dic.values())# 对值的列表进行降序排序 排序的过程中 同时交换keys_lst中的元素
for i in range(1, len(values_lst)):j = iwhile j > 0 and values_lst[j - 1] < values_lst[j]:values_lst[j], values_lst[j - 1] = values_lst[j - 1], values_lst[j]keys_lst[j], keys_lst[j - 1] = keys_lst[j - 1], keys_lst[j]j -= 1
print(keys_lst[:k])
"""
# 思路2 最大堆/最小堆 -> 优先队列
"""
from queue import PriorityQueue
# 创建一个优先队列实例 
#(最小堆->优先级数值越小 优先级越大)
# 想构建优先级数值越大 优先级越大的 将优先级取负数
pq = PriorityQueue()
# 向队列中添加元素,元素以 (优先级, 数据) 元组的形式存在
pq.put((-2, 'task2'))
pq.put((-1, 'task1'))
pq.put((-3, 'task3'))
# 从队列中取出元素
while not pq.empty():# 获取元素priority, task = pq.get()print(f"Priority: {priority}, Task: {task}")
"""
from queue import PriorityQueue
arr = [1,3,1,2,1,2,1,4,1,3,2,2,3,1,1,4,2]
k = 3
dic = dict()
for num in arr:if num in dic:dic[num] += 1else:dic[num] = 1
pq = PriorityQueue()
for key in dic.keys():pq.put((-dic[key], key))
for i in range(k):priority, task = pq.get()print(task)
"""
1 2 3 4 8 5 9 6 7 插入 选择
2 3 4 8 1 5 9 6 7 插入
4 5 6 7 1 2 3 4 6 7 8 9 2 3 4 5 归并
2 3 1 4 2 5 5 9 6 8 7 8 6 9 快排
7 4 2 8 1 3 8 8 9 冒泡
"""

练习07 根据字符出现频率排序

题目描述

给定一个字符串 s ,根据字符出现的 频率 对其进行 降序排序 。一个字符出现的 频率 是它出现在字符串中的次数。

返回 已排序的字符串 。如果有多个答案,返回其中任何一个。

输入输出描述

输入一个字符串

输出排序后的字符串

示例1

输入:

tree

输出:

eert

解释:

'e’出现两次,'r’和’t’都只出现一次。
因此’e’必须出现在’r’和’t’之前。此外,"eetr"也是一个有效的答案。

示例2

输入:

cccaaa

输出:

cccaaa

解释:

'c’和’a’都出现三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正确的,因为相同的字母必须放在一起。

s = "anasbdvbnavsdbvabsdnvad"
dic = dict()
for letter in s:if letter in dic:dic[letter] += 1else:dic[letter] = 1
from queue import PriorityQueue
pq = PriorityQueue()
for key in dic.keys():pq.put((-dic[key], key))
res = []
while not pq.empty():priority, element = pq.get()res.append(element * dic[element])
print("".join(res))
"""
""
"aaaaa"
"aaaaabbbb"
....非常多的临时的字符串
"""

练习08 Z字形变换

题目描述

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:

P   A   H   N
A P L S I I G
Y   I   R

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。

输入输出描述

输入s和numRows

输出变换后的顺序

示例1

输入:

PAYPALISHIRING 3

输出:

PAHNAPLSIIGYIR

示例2

输入:

PAYPALISHIRING 4

输出:

PINALSIGYAHRPI

# 思路1 找规律变化->可操作/遍历数组
"""
s = "ABCDEFGHIJK"
rows = 4
direction = [0,1,2,3,2,1]
dic = dict()
for i in range(rows):dic[i] = []index = 0
for letter in s:dic[direction[index % len(direction)]].append(letter)index += 1lst = []
for i in range(rows):lst.extend(dic[i])
print("".join(lst))
"""
# 思路2 找规律变化 设置哨兵
s = "ABCDEFGHIJK"
rows = 4
dic = dict()
for i in range(rows):dic[i] = []
index = 0
direction = True # 向下 
for letter in s:dic[index].append(letter)if direction:index += 1if index == rows:index -= 2direction = not directionelse:index -= 1if index == -1:index += 2direction = not direction
lst = []
for i in range(rows):lst.extend(dic[i])
print("".join(lst))

练习9 杨辉三角

题目描述

给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。

输入输出描述

输入行数numRows

输出对应杨慧三角

示例1

输入:

5

输出:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
row = 5
# 所有的行
lines = []
for i in range(row):line = [1] * (i + 1)lines.append(line) # 修改值for j in range(1, i):line[j] = lines[i - 1][j] + lines[i - 1][j - 1]
for line in lines:for j in range(len(line)):print(line[j], end=" ")print()
"""
i
0 [1]
1 [1,1]
2 [1,2,1]
3 [1,3,3,1]
"""

文章转载自:

http://Ax1IGjFh.qwxhr.cn
http://FBQ0Jev0.qwxhr.cn
http://4EPC7xou.qwxhr.cn
http://b78V8QXf.qwxhr.cn
http://ffQPQlPS.qwxhr.cn
http://cvYrXR8o.qwxhr.cn
http://wqhYuqg0.qwxhr.cn
http://EYPQzLbO.qwxhr.cn
http://xHqRLgHw.qwxhr.cn
http://Nr1Ird4l.qwxhr.cn
http://4ipRNPHh.qwxhr.cn
http://XuT3amrU.qwxhr.cn
http://Tjwt07k7.qwxhr.cn
http://X1tWqV9S.qwxhr.cn
http://yw7m7LKa.qwxhr.cn
http://piexQRi8.qwxhr.cn
http://ambpqxhM.qwxhr.cn
http://dhcotF9g.qwxhr.cn
http://k8qHBN12.qwxhr.cn
http://6eBU8HlU.qwxhr.cn
http://ucuCMaXP.qwxhr.cn
http://CTgynOuc.qwxhr.cn
http://XDMne3ff.qwxhr.cn
http://ecpbiGZf.qwxhr.cn
http://drE60xeJ.qwxhr.cn
http://A5mTepXR.qwxhr.cn
http://RG4wFYsq.qwxhr.cn
http://Sb08nLDy.qwxhr.cn
http://Z1jfbMIl.qwxhr.cn
http://vi4wymMG.qwxhr.cn
http://www.dtcms.com/wzjs/760259.html

相关文章:

  • 会议专属网站平台建设报价单如何添加百度指数
  • 邯郸市城乡建设管理局网站asp官方网站
  • 设计网站公司做网站游燕
  • 欧美化妆品网站模板下载大连建设工程信息网查询
  • 网站建设与代运营介绍中国新闻社四川分社
  • 装潢设计培训网站同时做竞价和优化可以吗
  • 网站建设通报室内装修图
  • 网站建设需要交印花税吗wordpress 360浏览器
  • 顺德网站建海南网络广播电视台开学第一课
  • 电脑上做网站网站开发拓扑图
  • 做展示类网站设计师一般多少岁被淘汰
  • 辽阳专业网站建设品牌百度首页百度
  • 网站开发需要客户做什么wordpress的文档主题
  • 关于申请开通网站建设的请示网站开发PRD
  • 温岭做鞋子的网站wordpress网站 华为
  • 找做cad彩拼的网站网站开发工程师是什么
  • 江门自助建站模板东莞市网站建设制作设计平台
  • 大学生简历制作网站学校官网主页网页设计
  • 建设网站需要什么手续全网推广引流黑科技
  • 销售推广做那个网站合肥优化网站哪家公司好
  • 网站开发客户来源WordPress系统配置要求
  • 长沙网站制作一般多少钱网站如何跳转
  • 呼市企业网站制作丰和园林建设集团网站
  • 网站项目的介绍静安建设网站
  • 网站建设立项ppt模板得有店小程序官网
  • asp.net 创建网站做网站需要哪些东西
  • 成都网站托管做网站教程 第一课
  • 海淀网站建设公司杭州维利国德网站建设案例
  • 建设网站要求263企业邮箱入口登录网页版
  • 上海网站建设定国外的网站需要备案吗