数据单元的变量替换(100)
输入描述:
- 输入一行单元格数据,用逗号分割每个单元格,尾部没有逗号,最多26个单元格,对应编号A-Z;
- 每个单元格内容包含:字母、数字、<> 单元格引用,如aCd<A>8u引用单元格A;
- 输入不存在循环引用,一个单元格只能引用一个其他的单元格;
输出描述:
输出所有单元格展开后的内容,单元格间用逗号分隔,处理出错则输出-1
示例1
输入:1,2<A>00
输出: 1,2100
示例2:
输入:<B>12,1
输出:112,1
示例3
输入:<B<12,1
输出:-1
示例4
输入:<B>12,1,a,2<A>00
输出:112,1,a,211200
方案1:
思路:
- 递归解析引用问题;
- 非字母数字,则为引用,需判断引用是否合法
# 解析每个带有引用的单元格
def parse_ref(cell):
global error_label, cells, result
left_arrow = cell.find("<")
right_arrow = cell.find(">")
if left_arrow >= 0 and right_arrow >= 0 and right_arrow - left_arrow == 2:
# 获取引用值
ref_idx = ord(cell[left_arrow + 1]) - 65
ref_val = cells[ref_idx] # 可能还包含引用
if ref_val.isalnum():
return cell[:left_arrow] + ref_val + cell[right_arrow + 1:]
else:
return cell[:left_arrow] + parse_ref(ref_val) + cell[right_arrow + 1:]
else:
error_label = True
return "-1"
# 输入一行单元格
cells = input().strip().split(",")
# 存储替换的单元格结果
result = ["" for _ in cells]
# 解析过程是否有错
error_label = False
for idx, cell in enumerate(cells):
if cell.isalnum():
result[idx] = cell
continue
else:
# 含有引用符号
r = parse_ref(cell)
result[idx] = r
if error_label:
print("-1")
break
# 输出结果
print(",".join(result))
方案2:
更加的直观,易于理解;
alist = input().strip().split(",")
restore_list = []
def has_ref(data):
flag = False
for c in data:
if c.isalnum():
continue
elif c in "<>" and data.count("<") == 1 and data.count(">") == 1 and data.index(">") - data.index("<") >= 2:
return True
else:
raise ValueError("非法的引用")
return flag
def restore_ref(data):
global alist
r = ""
flag = False
for c in data:
if flag is False and c.isalnum():
r += c
elif c == "<":
flag = True
elif flag and c.isalpha():
ref_index = ord(c) - 65
ref_data = alist[ref_index]
if has_ref(ref_data):
r += restore_ref(ref_data)
else:
r += ref_data
elif c == ">":
flag = False
return r
try:
for data in alist:
if has_ref(data):
restore_list.append(restore_ref(data))
else:
restore_list.append(data)
print(",".join(restore_list))
except Exception:
print(-1)
2835

被折叠的 条评论
为什么被折叠?



