python - Python:每个操作数的宽度最多为四位。否则,返回的错误字符串将是:错误:数字不能超过四位
问题描述
我会得到一个包含算术运算的列表。我必须检查是否有任何数字包含超过 4 位数字。
arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])
应该通过。
arithmetic_arranger(["32 + 698", "38011 - 2", "45 + 43", "123 + 49"])
应该返回一个错误。
这就是我已经走了多远:
def arithmetic_arranger(problems):
if len(problems) > 5:
print("Error: Too many Problems.")
else:
for problem in problems:
if "+" not in problem or "-" not in problem:
print("Error: Operator must be '+' or '-'.")
elif re.search('[a-zA-Z]', problem):
print("Error: Numbers must only contain digits.")
解决方案
最后五位数:
\d{5}
[0-9]{5}
只有 5 位或更多位的整数:
(?<!\d)(?<!\d\.)\d{5,}(?!\.?\d)
解释
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\d{5,} digits (0-9) (at least 5 times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
\.? '.' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
) end of look-ahead
整数部分有 5 位或更多位的数字:
(?<!\d)(?<!\d\.)\d{5,}(?!\d)
同上减号\.?
。
推荐阅读
- opencv - 如何使用 openCV 和 python tesseract 对具有白色前景的文本进行 ocr
- shell - 运行 shell 以检查服务器列表中是否存在目录并在文件中获取输出
- reactjs - 将选定的值传回给父组件 React Hook
- continuous-integration - 使用 GitLab CI/CD 构建和部署与在我自己的机器上做所有事情相比有什么优势?
- python - 如何从python中带有文本和数字的不同元组列表中获取所有字符串
- python - 如何修复python请求错误“期望值”
- kubernetes - Kubernetes入口未更新
- react-native - 在 React Native 中实现一个包含月份和日期的二维数组
- apache-nifi - 在 NiFi 中合并流文件
- reactjs - 在 react 中同时更新 redux 状态