经典例题(Python)
经典例题
1.if嵌套
1.用户输入账号
2.用户输入密码
3.判断用户的账号是不是alex
4.如果账号是alex在继续判断密码是不是alexdsb
5.账号和密码都正确提示用户alex就是一个dsb
6.如果账号正确密码错误提示密码错误
7.如果账号错误提示账号错误
user = input("请输入账号:")
pwd = input("请输入密码:")
if user == "alex":
if pwd == "alexdsb":
print("alex就是一个dsb")
else:
print("密码错误!")
else:
print("账号错误!")
user = input("请输入账号:")
pwd = input("请输入密码:")
2.车牌区域划分
车牌区域划分, 现给出以下车牌. 根据车牌的信息, 分析出各省的车牌持有量. (选做题)
cars = ['鲁A32444','鲁B12333','京B8989M','⿊C49678','⿊C46555','沪 B25041']
locals = {'沪':'上海', '⿊':'⿊⻰江', '鲁':'⼭东', '鄂':'湖北', '湘':'湖南'}
结果: {'⿊⻰江':2, '⼭东': 2, '上海': 1}
答案:cars = ['鲁A32444','鲁B12333','京B8989M','⿊C49678','⿊C46555','沪 B25041']
locals = {'沪':'上海', '⿊':'⿊⻰江', '鲁':'⼭东', '鄂':'湖北', '湘':'湖南'}
dic = {} # {}
for i in cars:
key = i[0] # 获取车牌的第一个字
if key in locals:
new_key = locals[key] # 结果的键
dic[new_key] = dic.get(new_key,0) + 1 #get到dic中键的值,每次加一
print(dic)
3.找小岛问题:
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。假设网格的四个边均被水包围。
思路:先找一个路地块.只要与他相邻的陆地,全都变成非0或1(但本身这一块1不变),可以是2,3...然后,都循环一遍后,就直接找还有几个1,就有几个岛
lst = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1]] def is_island(lst,i,j): if i < 0 or j < 0 or i >= len(lst) or j >= len(lst[i]): return if lst[i][j] == 1: lst[i][j] = 2 #只要是这个小岛上的都变成2,只保留原有的第一块1 is_island(lst,i,j-1) is_island(lst,i,j+1) is_island(lst,i+1,j) is_island(lst,i-1,j) else: return def count_island(lst): count = 0 for i in range(0,len(lst)): for j in range(0,len(lst[i])): if lst[i][j] == 1: #最后循环一遍地图,有一个1就是一个小岛 is_island(lst,i,j) count += 1 return count print(count_island(lst))
4.请编写一个python程序,每秒采集本机cpu使用率,并输出到文件中。
import psutil import time # cpu_res = psutil.cpu_percent()#查看当前电脑的cpu占用率 # print(cpu_res) # 每一秒获取获取cpu的占有率 --->持久化保存 # 如何将时间和对应的cpu占有率去匹配 while True: # 获取当前时间和cpu的占有率 t = time.localtime()#当前时间 cpu_time = '%d:%d:%d' % (t.tm_hour, t.tm_min, t.tm_sec) cpu_res = psutil.cpu_percent()#cpu占用率 print(cpu_res) # 保存在文件中 with open('cpu.txt', 'a+') as f:#写入文件,注意是a不是w f.write('%s %s \n' % (cpu_time, cpu_res)) time.sleep(1)#一秒后继续查询
5.数据格式处理:
假设前端同学通过接口向后端传了天猫的行业信息,例如: industry_list = [ { "parent_ind" : "女装", "name" : "连衣裙" }, { "name": "女装" }, { "parent_ind" : "女装", "name" : "半身裙" }, { "parent_ind" : "女装", "name" : "A字裙" }, { "name": "数码" }, { "parent_ind" : "数码", "name": "电脑配件" }, { "parent_ind" : "电脑配件", "name": "内存" }, ] 为了取用方便,我们希望可以将其转换为树状格式,例如: { "数码": { "电脑配件": { "内存" : {} } }, "女装" : { "连衣裙": {}, "半身裙": {}, "A字裙": {} } } 实现一个方法完成这个转换,时间复杂度请控制在O(n) def convert_format(data): pass
解题代码:
industry_list = [ { "parent_ind": "女装", "name": "连衣裙" }, { "name": "女装" }, { "parent_ind": "女装", "name": "半身裙" }, { "parent_ind": "女装", "name": "A字裙" }, { "name": "数码" }, { "parent_ind": "数码", "name": "电脑配件" }, { "parent_ind": "电脑配件", "name": "内存" }, ] def convert_format(data): # 核心思想就是利用地址共用,在add里面放所有能到达的字典的地址, # 而这些地址和dic中调用的内容都是一个地址,所以,修改add的内容就是改dic里的内容 dic = {} # 结果 add = {} # 所有字典的共用地址 spe = {} # 其他情况 for i in data: parent_ind = i.get('parent_ind') name = i.get('name') if not parent_ind: add[name] = dic.setdefault(name, {}) else: if parent_ind in dic: add[name] = dic.get(parent_ind).setdefault(name, {}) #地址共用 elif parent_ind in add: add[name] = add.get(parent_ind).setdefault(name, {})#地址共用 else: spe.setdefault(parent_ind, {}).setdefault(name, {})#地址共用 for k, v in spe.items(): add.setdefault(k, {}).update(v) return dic print(convert_format(industry_list))
6.数独解题(九宫格):
数独的解法需 遵循如下规则:
- 数字 1-9 在每一行只能出现一次。
- 数字 1-9 在每一列只能出现一次。
- 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 '.' 表示。
输入:board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
输出:[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sudoku-solver
class Solution: def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ def check(x, y, s): for i in range(9):#行和列不能有同数字 if board[i][y] == s or board[x][i] == s: return False for i in [0, 1, 2]:#3x3要保证1-9一样一个 for j in [0, 1, 2]: if board[x//3*3+i][y//3*3+j] == s: return False return True def start(cur): if cur == 81: return True x, y = cur // 9, cur % 9 if board[x][y] != '.': return start(cur + 1) for k in range(1, 10): s = str(k) if check(x, y, s): board[x][y] = s if start(cur + 1): return True board[x][y] = '.' return False start(0)