4.10 华为机试第二题的奇葩坑
如果大家和我一样感觉没问题,最后还是不通过可以看看。
较为明显的坑:
- 数字可能是多位,如12
- 括号有三种{[(
- 括号内可嵌套,3(a2[b])
然而我跳的坑就比较奇葩了。代码如下:(我找了1个半小时的错,最后考试出来十分钟就找到了,难受)
我赌一包辣条(我猜大部分人一眼看不出来代码的错)
# 看a和b是否是一组括号
def is_pair(a, b):
if a == '{':
if b == '}':
return True
else:
return False
if a == '(':
if b == ')':
return True
else:
return
if a == '[':
if b == ']':
return True
else:
return False
return False
# 是否是数字
def is_num(a):
if ord(a) <= ord('9') and ord(a) >= ord('0'):
return True
else:
return False
# 是否是kuo
def is_kuohao(a):
if a == '{':
return True
if a == '}':
return True
if a == '(':
return True
if a == ')':
return True
if a == '[':
return True
if a == ']':
return True
return False
def repeat_str(s, begin, end):
if begin==end:
return s[begin]
result = ''
idx = begin
kuohao = []
shuzi = 1
tmp_b = -1
tmp_e = -1
tmp_shu = -1
while idx <= end:
if is_num(s[idx]):
tmp_shu = idx
idx += 1
# 数字可能多位
while is_num(s[idx]):
idx += 1
# 这时候只要找到这个括号的起始位置即刻
shuzi = int(s[tmp_shu:idx]) # 保存倍数
kuohao.append(s[idx]) # 保存左括号
tmp_b = idx + 1 # 保存递归所需
# 找到该数字后的那对括号位置
while kuohao:
idx += 1
if is_kuohao(s[idx]):
# 是括号,如果匹配了括号栈里最后一个则退栈
if is_pair(kuohao[-1], s[idx]):
kuohao.pop()
else:
kuohao.append(s[idx])
tmp_e = idx - 1
idx += 1
# 拼接递归的结果
result = result + (repeat_str(s, tmp_b, tmp_e) * shuzi)
else:
result = result + s[idx]
idx += 1
return result
while True:
try:
in_str = input()
result = repeat_str(in_str, 0, len(in_str) - 1)
print(result[::-1])
except:
break
错误在:倒数部分,
idx+=1
# 拼接递归的结果
这个注释上面一行的,idx+=1.
忘记了while循环会有idx+=1,这里画蛇添足了。所以前面的基本没有错,但是如果循环部分在前面就会有错,当时试的太少了。。。而且迷惑性也太强了吧!前面试了半天感觉没错,居然死在这,最后通过还是0%。。。
总结:例子一定要多试,如果通不过肯定是有坑!
#华为##笔试题目##春招#