| 试题编号: | 201612-3 |
| 试题名称: | 权限查询 |
| 时间限制: | 1.0s |
| 内存限制: | 256.0MB |
| 问题描述: | 问题描述 授权 (authorization) 是各类业务系统不可缺少的组成部分,系统用户通过授权机制获得系统中各个模块的操作权限。 输入格式 输入第一行是一个正整数 p,表示不同的权限类别的数量。紧接着的 p 行被称为 P 段,每行一个字符串,描述各个权限。对于分等级权限,格式为 <category>:<level>,其中 <category> 是权限类名,<level> 是该类权限的最高等级。对于不分等级权限,字符串只包含权限类名。 输出格式 输出共 q 行,每行为 false、true,或者一个数字。false 表示相应的用户不具有相应的权限,true 表示相应的用户具有相应的权限。对于分等级权限的不带等级查询,如果具有权限,则结果是一个数字,表示该用户具有该权限的(最高)等级。如果用户不存在,或者查询的权限没有定义,则应该返回 false。 样例输入 3 样例输出 false 样例说明 样例输入描述的场景中,各个用户实际的权限如下: 评测用例规模与约定 评测用例规模: |
一、解题思路分析
1.依次读入用户输入数据,个人认为权限类型没有什么用,其他的化为如下形式:
(1)role = {'hr': ['crm:2'], 'it': ['crm:1', 'git:1', 'game'], 'dev': ['git:3', 'game'], 'qa': ['git:2']}
(2)old_user = {'alice': ['crm:2'], 'bob': ['crm:1', 'git:1', 'game', 'git:2'], 'charlie': ['git:3', 'game']}
2.重点,我们需要查询某个用户是否有某种权限。观察old_user中存在:权限:等级,这种我们不好匹配
3.修改old_user,便于查询,形式如下:
(1)new_user = {'alice': ['crm', 2], 'bob': ['crm', 1, 'git', 2, 'game'], 'charlie': ['git', 3, 'game']}
(2)将old_user中的"权限:等级"改为:“权限”,“等级”,等级记录用户最高的等级(终点)
4.查询用户是否具有某种权限
(1)首先检验查询用户是否在new_user中;
(2)分情况:查询权限包括等级或者不包括等级
二、满分代码
# 权限类别
p = int(input())
gtype = []
for i in range(p):temp = input().strip()gtype.append(temp)# 角色
r = int(input())
role = {}
for i in range(r):temp = input().split()role[temp[0]] = []t = int(temp[1])for j in range(t):role[temp[0]].append(temp[2+j])##print(role)# old_user
u = int(input())
user = {}
for i in range(u):temp = input().split()user[temp[0]] = []t = int(temp[1])for j in range(t):r = temp[2+j]user[temp[0]].extend(role[r])##print(user)# 修改old_user,将“权限:等级”改为“权限”,“等级”
for key, value in user.items():length = len(value)i = 0while i < length: if ':' in str(value[i]): # 若包含等级temp = value[i].split(':')try: # value中包含temp[0]ind = value.index(temp[0]) if isinstance(value[ind+1], int):if value[ind+1] < int(temp[1]): # 修改最高等级user[key][ind+1] = int(temp[1]) user[key].pop(i) length -= 1except: # value中不包含temp[0]user[key][i] = temp[0]user[key].insert(i+1, int(temp[1])) i += 2length += 1else:i += 1##print(user)# 用户需要查询的权限
q = int(input())
result = []
for i in range(q):temp = input().split()u, grant = tempif u not in user.keys(): # 用户不存在result.append('false')continuelength = len(user[u])# 不包含等级if ":" not in grant:if grant in user[u]: # 能查到权限ind = user[u].index(grant)if ind == length - 1 or not isinstance(user[u][ind+1], int): # 最后一个权限,即后面没有等级,直接返回trueresult.append('true')else: # 后面跟着等级result.append(user[u][ind+1]) # 分等级权限的不带等级查询else:result.append('false')# 包含等级else:temp = grant.split(':')grant, level = temp[0], int(temp[1])if grant in user[u]:ind = user[u].index(grant)if ind == length - 1 or not isinstance(user[u][ind+1], int):result.append('false')else: if user[u][ind+1] >= level:result.append('true')else:result.append('false')else:result.append('false')
for i in result:print(i)