Arithmetic Formatter

I dont understand what goes wrong in this code.
I get correct output with trial and error, but repl.it is showing error.

def arithmetic_arranger(problems,op = False):
  lst=["+","-"]
  s1=''
  s2=''
  s3=''
  s4=''
  if len(problems)>5:
      return "Error: Too many problems."
  for ele in problems:
    ele_list=ele.split()
    if ele_list[1] not in lst:
      return "Error: Operator must be '+' or '-'."
    if ele_list[0].isnumeric()==False or ele_list[2].isnumeric()==False:
      return "Error: Numbers must only contain digits."
    if len(ele_list[0])>4 or len(ele_list[2])>4:
      return "Error: Numbers cannot be more than four digits."
    x = max(len(ele_list[0]),len(ele_list[2]))
    s1+=ele_list[0].rjust(x+2)+'    '
    s2+=ele_list[1]+(' '+ele_list[2]).rjust(x+1)+'    '
    s3+=('-'*(x+2))+'    '
    if op:
      if ele_list[1]=='+':
        s4+=str(int(ele_list[0])+int(ele_list[2])).rjust(x+2)+'    '
      else:
        s4+=str(int(ele_list[0])-int(ele_list[2])).rjust(x+2)+'    '
    arranged_problems=s1+'\n'+s2+'\n'+s3+'\n'+s4
  return arranged_problems

Hello!

The output has trailing spaces, which is not expected in the tests:

   32         1      45      123    
- 698    - 3801    + 43    +  49    
-----    ------    ----    -----    
 -666     -3800      88      172

Expected

   32         1      45      123
- 698    - 3801    + 43    +  49
-----    ------    ----    -----
 -666     -3800      88      172
1 Like

Thank you for your help!
Now I am still getting an error with 1 test case, after removing the trailing white spaces :frowning:

def arithmetic_arranger(problems,op = False):
  lst=["+","-"]
  s1=''
  s2=''
  s3=''
  s4=''
  if len(problems)>5:
      return "Error: Too many problems."
  for ele in problems:
    ele_list=ele.split()
    if ele_list[1] not in lst:
      return "Error: Operator must be '+' or '-'."
    if ele_list[0].isnumeric()==False or ele_list[2].isnumeric()==False:
      return "Error: Numbers must only contain digits."
    if len(ele_list[0])>4 or len(ele_list[2])>4:
      return "Error: Numbers cannot be more than four digits."
    x = max(len(ele_list[0]),len(ele_list[2]))
    s1+=ele_list[0].rjust(x+2)+'    '
    s2+=ele_list[1]+(' '+ele_list[2]).rjust(x+1)+'    '
    s3+=('-'*(x+2))+'    '
    if op:
      if ele_list[1]=='+':
        s4+=str(int(ele_list[0])+int(ele_list[2])).rjust(x+2)+'    '
      else:
        s4+=str(int(ele_list[0])-int(ele_list[2])).rjust(x+2)+'    '
      arranged_problems=s1.rstrip()+'\n'+s2.rstrip()+'\n'+s3.rstrip()+'\n'+s4.rstrip()
      return arranged_problems
  arranged_problems=s1.rstrip()+'\n'+s2.rstrip()+'\n'+s3.rstrip()
  return arranged_problems

This is my modified code.

You’re now returning before the loop ends if op == True :sweat_smile::

Just to clarify, you’re not iterating over every problem passed to the function :slight_smile:.

1 Like

Oh… my bad !
Thank you once again!
I woudn’t have noticed that :sweat_smile:

1 Like