【问题标题】:Arithmetic Formatter Help Output算术格式化程序帮助输出
【发布时间】:2021-08-11 12:18:34
【问题描述】:

所以我几乎完成了www.freeCodeCamp.org 中要求我完成的算术格式化程序。计算必须垂直内联显示,如果我们添加一个 True 语句,那么我们将能够看到计算的结果。它会是这样的:

arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])

输出:没有结果的内联计算:

(现在有计算)

arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True)

输出:带结果的内联计算:

所以我已经完成了我的代码,但我仍然有 5 个错误和 1 个失败。

这是我的代码:

def arithmetic_arranger(problems, see = True):

  first_operand = list()
  operator = list()
  second_operand = list()
  max_length = list()
  dashes = list()
  operation = list()
  upper_part = ""
  lower_part = ""
  dashesline = ""
  results = ""
  index = 0

  # Get the length of the list, if it is higher than 5, print an error 
  if len(problems) > 5:
    print(" Error: Too many problems")

  # Divide the list into sub lists
  for increment in problems:
    new_item = increment.split()

    # Assign first, second operand and operator
    first_operand.append(new_item[0])
    operator.append(new_item[1])
    second_operand.append(new_item[2])

  # Checking if the operands are only digits (must be separated into 
  # two different for loops if we do not want to see the error written 4 times)
  for go_over in first_operand:
    if not go_over.isnumeric():
      print("Error: Numbers must only contain digits")
  for go_over in second_operand:
    if not go_over.isnumeric():
      print("Error: Numbers must only contain digits")

  # Checking if numbers are not above 4 digits (must be separated into 
  # two different for loops if we do not want to see the error written 4 times)
  for go_over in first_operand:
    if len(go_over) > 4:
      print("Error: Numbers cannot be more than four digits")
  for go_over in second_operand:
    if len(go_over) > 4:
      print("Error: Numbers cannot be more than four digits")
        
  # Checking if the operator is a '+' or a '-'
  for go_over in operator:
    index += 1
    if go_over == "*" or go_over == "/":
      print("Error: Operator must be '+' or '-'")
    # Doing the calculation for '+' and '-'
    elif go_over == "+":
      operation.append(str(int(first_operand[index-1]) + int(second_operand[index-1])))
    elif go_over == "-":
      operation.append(str(int(first_operand[index-1]) - int(second_operand[index-1])))

  for go_over in range(len(first_operand)):
    max_length.append(max(len(first_operand[go_over]),len(second_operand[go_over])))
    dashes.append("-"*(2+max_length[go_over]))
  
  for go_over in range(len(first_operand)):
    if see == True:
      if go_over == 0:
        upper_part += first_operand[go_over].rjust(2+max_length[go_over])
        lower_part += operator[go_over].ljust(0) + " " + second_operand[go_over]
        dashesline += dashes[go_over]
        results += operation[go_over].rjust(2+max_length[go_over])
      else:
        upper_part += "    " + first_operand[go_over].rjust(2+max_length[go_over])
        lower_part += "    " + operator[go_over].ljust(0) + " " + second_operand[go_over].rjust(max_length[go_over])
        dashesline += "    " + dashes[go_over]
        results += "    " + operation[go_over].rjust(2+max_length[go_over])
        
      arranged_problems = upper_part + "\n" + lower_part + "\n" + dashesline + "\n" + results

    else:
      if go_over == 0:
        upper_part += first_operand[go_over].rjust(2+max_length[go_over])
        lower_part += operator[go_over].ljust(0) + " " + second_operand[go_over]
      else:
        upper_part += "    " + first_operand[go_over].rjust(2+max_length[go_over])
        lower_part += "    " + operator[go_over].ljust(0) + " " + second_operand[go_over].rjust(max_length[go_over])
        
      arranged_problems = upper_part + "\n" + lower_part
    
    return arranged_problems

这是来自控制台的响应:

python main.py
   32
+ 698
-----
  730
EEEFEE
======================================================================
ERROR: test_arrangement (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-13/test_module.py", line 8, in test_arrangement
    actual = arithmetic_arranger(["3 + 855", "3801 - 2", "45 + 43", "123 + 49"])
TypeError: arithmetic_arranger() missing 1 required positional argument: 'see'

======================================================================
ERROR: test_incorrect_operator (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-13/test_module.py", line 22, in test_incorrect_operator
    actual = arithmetic_arranger(["3 / 855", "3801 - 2", "45 + 43", "123 + 49"])
TypeError: arithmetic_arranger() missing 1 required positional argument: 'see'

======================================================================
ERROR: test_only_digits (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-13/test_module.py", line 32, in test_only_digits
    actual = arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"])
TypeError: arithmetic_arranger() missing 1 required positional argument: 'see'

======================================================================
ERROR: test_too_many_digits (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-13/test_module.py", line 27, in test_too_many_digits
    actual = arithmetic_arranger(["24 + 85215", "3801 - 2", "45 + 43", "123 + 49"])
TypeError: arithmetic_arranger() missing 1 required positional argument: 'see'

======================================================================
ERROR: test_too_many_problems (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-13/test_module.py", line 17, in test_too_many_problems
    actual = arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"])
TypeError: arithmetic_arranger() missing 1 required positional argument: 'see'

======================================================================
FAIL: test_solutions (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-13/test_module.py", line 39, in test_solutions
    self.assertEqual(actual, expected, 'Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with arithmetic problems and a second argument of `True`.')
AssertionError: '   32\n- 698\n-----\n -666' != '   32         1      45      123\n- 698    - 3[84 chars] 172'
-    32
- - 698
- -----
-  -666+    32         1      45      123
+ - 698    - 3801    + 43    +  49
+ -----    ------    ----    -----
+  -666     -3800      88      172 : Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with arithmetic problems and a second argument of `True`.

----------------------------------------------------------------------
Ran 6 tests in 0.002s

FAILED (failures=1, errors=5)

【问题讨论】:

  • 抱歉,您发布的代码(默认为see)无法导致该回溯。你忘了把它复制到某个地方吗?

标签: python string list for-loop if-statement


【解决方案1】:

我已从您的解决方案开始,并通过执行以下一些操作来重构代码:

  • 提取方法
  • 重命名事物
  • 引入解释性局部变量
  • 引入全局变量(减少方法参数的数量)
  • 使用断言而不是打印行(为了在第一个输入错误时退出)
  • ...

最后,我采用了两个单独的步骤来解决您的问题(请参阅下面的完整代码):

  • 处理输入
  • 构建输出

希望这可以帮助您找到问题所在。 我可以发现的一件事是,您没有在最终循环中连接每一行的问题部分,而是始终重新分配 arranged_problems 变量。

这是我建议的解决方案,它并不旨在完美,但应该有助于理解正在发生的事情:

MAX_NUM_OF_PROBLEMS = 5
MAX_OPERAND_LEN = 4

first_operands = list()
operators = list()
second_operands = list()
results = list()


def arithmetic_arranger(problems, show_results = True):
  process_input(problems)

  return build_output(show_results)


def process_input(problems):
  assert len(problems) <= MAX_NUM_OF_PROBLEMS, "ERROR: Too many problems"

  for problem in problems:
    parts = problem.split()

    assert len(parts) == 3, "ERROR: problems must have 2 operands and 1 operator"

    t1 = parts[0]
    op = parts[1]
    t2 = parts[2]

    assert t1.isnumeric() and t2.isnumeric(), "ERROR: operands must only contain digits"
    assert len(t1) <= MAX_OPERAND_LEN and len(t2) <= MAX_OPERAND_LEN, "ERROR: operands must not have more than " + MAX_OPERAND_LEN + " digits"
    assert op == "+" or op == "-", "ERROR: operator must be '+' or '-'"

    first_operands.append(t1)
    operators.append(op)
    second_operands.append(t2)
    result = ""
    if op == "+":
      result = str(int(t1) + int(t2))
    else: # we checked for + or - above
      result = str(int(t1) - int(t2))
    results.append(result)


def build_output(show_results):
  spacer = " " * 3
  line1 = ""
  line2 = ""
  dashes = ""
  line3 = ""

  for index in range(len(first_operands)):
    t1 = first_operands[index]
    op = operators[index]
    t2 = second_operands[index]
    result = results[index]
    width = max(len(t1), len(t2))

    line1 += spacer + " " + " " + t1.rjust(width)
    line2 += spacer + op + " " + t2.rjust(width)
    dashes += spacer + "-" * (width + 2)
    line3 += spacer + " " * (2 - len(result) + width) + result

  output = line1 + "\n" + line2 + "\n"
  if show_results:
    output += dashes + "\n" + line3 + "\n"
  return output

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2010-09-07
    相关资源
    最近更新 更多