Tests fail except for error messages (6 fail 4 pass)

Tell us what’s happening:
My Long String (finalstr) is identical, character for character, to the one in the Assert, but All test samples with valid parameters fail. Only the 4 with error messages pass.

The Final String (finalstr) is raw string data. I’ve added single quotes to beginning and end. Took the single quotes out again because it made no difference.
I don’t know what to do next.

It’s my first time using Replit, so have not made/found a URL yet (I suppose that comes from publishing it …)
[I could not find Python template in codesandbox, which I used for the javascript certification]

Your code so far

def arithmetic_arranger(data: list, giveanswer = False) -> str:
    """
        Scientific calculator for students- addition and subtraaction sums displayed vertically.
        Split problems into 3 lines of numbers (plus lengths)
            top number, bottom number and answer
    """
    # your code here
    def makeline(linelist,collist,oprlist = list(),dashes = False,nl = True):
        """
        Args: - all 3 arguments are lists -
            linelist ([int or str]): line to print, whether numbers or dashes
            collist ([int]): widths of columns (based on lengths of strings)
            oprlist ([str], optional): operators. Defaults to (empty) list()
            dashes (bool), optional: print dashes Defaults ro False
            nl (bool),optional: new line between each line
        """
        printstr = ""
        opch = " " # space to line up numbers with no operator
        i = 0 # index for syncronised lists
        if nl:
            printstr += "\\n" # if nl is True, add New Line at start
            print("") # print a new line
        for colpr in linelist:
            colwidth = collist[i]-1
            if oprlist != []:
                opch = oprlist[i] # operator
            if dashes:
                opch = "" # NO SPACE for dashes
            
            if i != 0: # 4 spaces between (so none for 1st column)
                printstr += f" "*4
                print(f" "*4,end="")
            if isinstance(colpr,int):
                printstr += f"{opch}{colpr:{colwidth}d}"
                print(f"{opch}{colpr:{colwidth}d}",end="")
            else:
                printstr += f"{opch}{colpr:{colwidth}}"
                print(f"{opch}{colpr:{colwidth}}",end="")
            i += 1 # next index for syncronised lists
        # -for colpr in linelist
        
        return printstr
    # -def makeline(linelist,dashes = False)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    import re
    #print("\n:",data, giveanswer,"\n")
    maxprob = 5
    finalstr = r"" #raw string- for \n in output
    if len(data) > maxprob:
        print("Error: Too many problems (max ",maxprob,")\n")
        return "Error: Too many problems."
    # all these lists are syncronised with each other
    oplist = list()
    num1list = list()
    num2list = list()
    dashlist = list()
    num3list = list()
    lenlist = list()
    # split into 3 lines, operators, dashes plus lengths
    for tx in data:
        x = re.findall(r"\b[\d]+\b",tx) # numbers
        op = re.findall(r"[\-\+]",tx) # PLUS  /  MINUS operator
        y = re.findall(r"[A-Za-z]+",tx) # Error- contains letters
        if y != []:
            print("Error: cannot contain letters. It must only contain numbers and the '+' or '-' operators.\n")
            return "Error: Numbers must only contain digits."
        if len(x) != 2:
            print("Error: Need 2 numbers for an addition or subtraction sum\n")
            return "Error: Need 2 numbers for an addition or subtraction sum"
        if len(op) != 1:
            print("Error: Need 1 operator '+' or '-' between the numbers\n")
            return "Error: Operator must be '+' or '-'."
        str1 = x[0]
        num1 = int(str1)
        str2 = x[1]
        num2 = int(str2)
        if len(str1) > 4 or len(str2) > 4:
            print("Error: each number can be up to 4 digits long\n")
            return "Error: Numbers cannot be more than four digits."
        # must allow for longest number + space + operator (length +2)
        if len(str1) > len(str2):
            maxlen = len(str1)+2
        else:
            maxlen = len(str2)+2
        num1list.append(num1) # 1st line of numbers 
        num2list.append(num2) # 2nd line of numbers
        oplist.append(op[0])
        if op[0] == "+":
            num3 = num1 + num2
        else:
            num3 = num1 - num2
        num3list.append(num3) # answer- 3rd line of numbers 
        dashlist.append("".ljust(maxlen,"-")) # dashes
        lenlist.append(maxlen) # length of strings- for column width
    # -for tx in data:
    # now display the columns of numbers, line by line
    finalstr += makeline(num1list,lenlist,nl = False) # 1st line no \n
    finalstr += makeline(num2list,lenlist,oplist) # 2nd line
    finalstr += makeline(dashlist,lenlist,dashes=True) # line of dashes
    if giveanswer:
        finalstr += makeline(num3list,lenlist) # line of answers (if needed)
    print("\n")
    print(finalstr)
    print("\n123456789o123456789o123456789o123456789o123456789o") # character counter on screen to check alignment
    print("")
    return finalstr

ASSERT:
_______________ test_template[test_five_problems_with_solutions] _______________

arguments = [[‘32 - 698’, ‘1 - 3801’, ‘45 + 43’, ‘123 + 49’, ‘988 + 40’], True]
expected_output = ’ 32 1 45 123 988\n- 698 - 3801 + 43 + 49 + 40\n----- ------ ---- ----- -----\n -666 -3800 88 172 1028’
fail_message = ‘Expected solutions to be correctly displayed in output when calling “arithmetic_arranger()” with five arithmetic problems and a second argument of True.’

@pytest.mark.parametrize('arguments,expected_output,fail_message', test_cases)
def test_template(arguments, expected_output, fail_message):
    actual = arithmetic_arranger(*arguments)
  assert actual == expected_output, fail_message

E AssertionError: Expected solutions to be correctly displayed in output when calling “arithmetic_arranger()” with five arithmetic problems and a second argument of True.
E assert ’ 32 … 172 1028’ == ’ 32 … 172 1028’
E + 32 1 45 123 988\n- 698 - 3801 + 43 + 49 + 40\n----- ------ ---- ----- -----\n -666 -3800 88 172 1028
E - 32 1 45 123 988
E - - 698 - 3801 + 43 + 49 + 40
E - ----- ------ ---- ----- -----
E - -666 -3800 88 172 1028

test_module.py:77: AssertionError
----------------------------- Captured stdout call -----------------------------
32 1 45 123 988

  • 698 - 3801 + 43 + 49 + 40

-666 -3800 88 172 1028

32 1 45 123 988\n- 698 - 3801 + 43 + 49 + 40\n----- ------ ---- ----- -----\n -666 -3800 88 172 1028

123456789o123456789o123456789o123456789o123456789o

========================= 6 failed, 4 passed in 0.14s ==========================
Your browser information:

MS Edge in win10
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62

Challenge: Arithmetic Formatter

Link to the challenge:

Is escaping new line character intended?

That code seems a LOT longer that the usual solutions I see around here. That already makes it a bit harder to read and follow, as even with comments, some things seem overcomplicated.

And the main issue is, we at least need the raw error message to figure out an issue. Easiest way to get those is from the replit directly. Or at least if you copy-paste them, make sure you use the forum-option to have them displayed as code.

Yes. New line must be escaped to add to the string.

How then it’s going to be printed out as a new line, if it’s escaped? That won’t add an actual new line.

I’m kinda old school- was a programmer 25 years ago (before some of you were born, maybe?)
I tend to use the old, simpler ways. I will have to get used to the new, more powerful ways, but I just do what I know when getting the logic figured out and the coding done.

Um. This is my first time in Replit. Forum option ?

If it wasn’t clear, I’m referring to this line:

            printstr += "\\n" # if nl is True, add New Line at start

It does add a \n to the string.
Seems to be a Python thing. . .

See 3.2 The Backslash Plague (uhcl.edu)

Hi Jagaya

I still have not been able to find the Forum Mode.

Obviously I will have to re-research the shorter forms of function notation and lambda functions and all that.

There is power in these newer languages that just was not there in the old days. I will just have to wrap my mind around it…

I guess I’m in too much of a hurry to get certification so I can look for work.

I think I have a strategy for the solution of this challenge.

It adds literally \n to the string, it doesn’t add new line character.

>>> print('a\\nb')
a\nb
>>> print('a\nb')
a
b

When you write a comment, above the text-field is a bunch of symbols - the “</>” one formats text into code.

I often recommend w3schools.com - they have a lot of info on several languages and packages. Also some kind of code-challenges though those are just stupidly easy.

So… I clearly did not understand the whole Backslash Plague thing.

I took out the extra backslash, and it passes all 10 tests

Go figure

That page refers more to regex matching, where backslash might be wanted to be matched.

Cool. Thanks for the info. Appreciate the help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.