首页 > 解决方案 > 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.")

标签: pythonregex

解决方案


最后五位数:

\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)

同上减号\.?


推荐阅读