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

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://www.xdnf.cn/news/15380.html

相关文章:

  • Vim多列操作指南
  • TCP可靠性设计的核心机制与底层逻辑
  • next.js 登录认证:使用 github 账号授权登录。
  • uni-app+vue3 来说一说前端遇到跨域的解决方案
  • 全连接神经网络
  • 10分钟搞定!Chatbox+本地知识库=你的私人语音导师:企业级全栈实现指南
  • 自动微分模块
  • JAR 包冲突排雷指南:原理、现象与 Maven 一站式解决
  • 机载激光雷达目标识别:从点云到凝视成像的算法全景
  • Datawhale AI夏令营——用户新增预测挑战赛
  • xss-lab靶场通关
  • 苦练Python第18天:Python异常处理锦囊
  • 从 JSON 到 Python 对象:一次通透的序列化与反序列化之旅
  • 云原生技术与应用-Containerd容器技术详解
  • Android系统的问题分析笔记 - Android上的调试方式 bugreport
  • RAG索引流程中的文档解析:工业级实践方案与最佳实践
  • iOS —— 网易云仿写
  • 大数据系列之:通过trino查询hive表
  • 直播推流技术底层逻辑详解与私有化实现方案-以rmtp rtc hls为例-优雅草卓伊凡
  • 在Linux下git的使用
  • 量子计算新突破!阿里“太章3.0”实现512量子比特模拟(2025中国量子算力巅峰)
  • MYOJ_8512:CSP初赛题单1:计算机常识
  • 计算机网络通信的相关知识总结
  • Linux进程优先级机制深度解析:从Nice值到实时调度
  • 图机器学习(1)——图论基础
  • Django Admin 配置详解
  • 【C语言进阶】指针面试题详解(2)
  • 玩转Docker | 使用Docker部署TeamMapper思维导图应用程序
  • 使⽤Pytorch构建⼀个神经⽹络
  • Android Studio C++/JNI/Kotlin 示例 三