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

Python初学者笔记第十二期 -- (集合与字典编程练习题)

第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://burberry.wjrtg.cn
http://alongshore.wjrtg.cn
http://augural.wjrtg.cn
http://bebeeru.wjrtg.cn
http://catling.wjrtg.cn
http://bento.wjrtg.cn
http://bedad.wjrtg.cn
http://animator.wjrtg.cn
http://bez.wjrtg.cn
http://aleph.wjrtg.cn
http://brucine.wjrtg.cn
http://bucaramanga.wjrtg.cn
http://chloroacetic.wjrtg.cn
http://anhemitonic.wjrtg.cn
http://administer.wjrtg.cn
http://amphineura.wjrtg.cn
http://aftertax.wjrtg.cn
http://cardiant.wjrtg.cn
http://bepuzzle.wjrtg.cn
http://bowed.wjrtg.cn
http://bittock.wjrtg.cn
http://aeneid.wjrtg.cn
http://autoroute.wjrtg.cn
http://bechuana.wjrtg.cn
http://ammonotelism.wjrtg.cn
http://cheesemaker.wjrtg.cn
http://bomb.wjrtg.cn
http://anime.wjrtg.cn
http://ceratoid.wjrtg.cn
http://announceable.wjrtg.cn
http://www.dtcms.com/a/281146.html

相关文章:

  • U-Boot 中增加 GIC-400中断服务程序
  • Copula理论:覆盖相关性分析、极值相依性、回归建模、时间序列预测、贝叶斯网络,R/Python双语言实现+AI编程辅助(科研绘图与结果呈现)
  • Nestjs框架: 数据库多租户模式与动态模块初探
  • Oracle日期时间函数说明及与MySql区别说明
  • 同济医院R语言训练营第三期开讲!上交大张维拓老师主讲
  • RabbitMQ工作流程
  • SQL学习记录01
  • 15.图像 模板轮廓检测
  • 李白周游记50篇
  • linux-develop
  • 基于Alpine构建MySQL镜像
  • 第二阶段-第二章—8天Python从入门到精通【itheima】-129节(MySQL的安装)
  • 【前后端】Node.js 模块大全
  • 巨坑检查无误还报错is not mapped MappingException: Unknown entity:@Entity
  • DeepSWE:通过强化学习扩展训练开源编码智能体
  • 多层 `while` 循环中,`break` 的行为
  • ES2023 新特性解析_数组与对象的现代化操作指南
  • 二分查找栈堆
  • 【C语言进阶】字符函数和字符串函数的内部原理
  • “ModuleNotFoundError“深度解析:Python模块导入问题的终极指南
  • PHP语言基础知识(超详细)第二节
  • OSPFv3中LSA参数
  • dbever 导出数据库表的建表语句和数据插入语句
  • 嵌入式Linux:进程间通信机制
  • AJAX 开发中的注意点
  • ASRPRO系列语音模块(第十天)
  • AI 增强大前端数据加密与隐私保护:技术实现与合规遵
  • Python 程序设计讲义(2):Python 概述
  • pc浏览器页面语音播报功能
  • 多路文件IO的几个模型