ArithmeticFormatter identical to solution does not pass

Here is my code for the exercise:

def arithmetic_arranger(problems, show_answers=True):
    """problems is a list of strings"""
    first_row       = [] # implemento le righe come liste
    second_row      = []
    separator_row   = []
    result_row      = []

    for pb in problems:
        addend_list = pb.split(' ')         # separo numeri e segno
        addend_1 = addend_list[0]           
        sign     = addend_list[1]
        addend_2 = addend_list[2]

        row_length = max(len(addend_list[0]),len(addend_list[2])) + 2       
        first_row.append(' '*(row_length-len(addend_list[0])) + addend_list[0])        #prima riga
        second_row.append(sign + ' '*(row_length-len(sign)-len(addend_2)) + addend_2)  #seconda riga
        separator_row.append('-'*row_length)                                           #riga separatrice

        if show_answers:          # controllo per visualizzazione risultato
            if sign == '+':
                result = int(addend_1) + int(addend_2)
            elif sign == '-':
                result = int(addend_1) - int(addend_2)
            result_row.append(' '*(row_length-len(str(result))) + str(result))

    # Unire gli elementi di ciascuna lista con quattro spazi e stampare le righe risultanti
    print('    '.join(first_row))
    print('    '.join(second_row))
    print('    '.join(separator_row))
    if show_answers:
        print('    '.join(result_row))


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

So my code works properly since it display the correct formatting, however something seems to be wrong and I cannot see what since indeed the requested solution is identical to mine. Can anyone help me?

Thanks in advance,
Riccardo

Edit: okay I need to handle errors first :slight_smile:, I did not recognise error handling was missing.

Your function needs to return the result as a single string, not print anything.

If you want to see the result, print the result of the function:

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

So I have to add return problems at the end of the function?

Edit: so I need to restart from beginning? Here I just have a ā€œvoidā€ function (C++ - speaking) which prints the results, isnā€™t the same output as giving the entire string as result?

Yes, you need to use the return keyword.

You can probably just modify your print() lines. Instead of printing, they should concatenate each line into a single string which you will then return.

If you look at the tests, they show you exactly what the returned string should look like.

In the instructions youā€™ll see something along the lines of ā€œYour function should return a single stringā€, which is a bit different than printing many lines.

Understood, I thought to be done with this exercise, however I will need to change it a bit. In my opinion it was not so clear that in standard mode - so when no error occurs - the output should also be a string itself. I did that for errors handling, but it wasnā€™t evident one had to to the job withouh ant print() function callings.

However thanks a lot,
Iā€™ll work again on this project!
Riccardo

I agree, itā€™s easy to miss this part of the instructions and many people do. Let us know if you have an idea of how to best make it more clear?

But this is a reminder that whenever you see the word ā€œreturnā€ it definitely means return in big, glowing letters.

1 Like

I updated my code, and now it works with no print function calling inside the main function arithmetic_arranger(). Iā€™m wondering now why this version is not acceptedā€¦

def arithmetic_arranger(problems, show_answers=True):
    """problems is a list of strings"""
    first_row       = [] # implemento le righe come liste
    second_row      = []
    separator_row   = []
    result_row      = []

    for pb in problems:
        addend_list = pb.split(' ')         # separo numeri e segno
        addend_1 = addend_list[0]  
        # checking addend_1 length
        if (len(addend_1) > 4):
            print("Error: Numbers cannot be more than four digits.")
            break
        if contiene_alfabetici(addend_1) == True:
            print("Error: Numbers must only contain digits")
            break
        # checking correct operator insertion
        if (addend_list[1] == '*'):
            print("Error: Operator must be '+' or '-'.")
            break      
        if (addend_list[1] == '/'):
            print("Error: Operator must be '+' or '-'.")
            break      
        sign     = addend_list[1]
        addend_2 = addend_list[2]
        # checking addend_2 length
        if (len(addend_2) > 4):
            print("Error: Numbers cannot be more than four digits.")
            break
        if contiene_alfabetici(addend_2) == True:
            print("Error: Numbers must only contain digits")
            break

        row_length = max(len(addend_list[0]),len(addend_list[2])) + 2       
        first_row.append(' '*(row_length-len(addend_list[0])) + addend_list[0])        #prima riga
        second_row.append(sign + ' '*(row_length-len(sign)-len(addend_2)) + addend_2)  #seconda riga
        separator_row.append('-'*row_length)                                           #riga separatrice

        if show_answers:          # controllo per visualizzazione risultato
            if sign == '+':
                result = int(addend_1) + int(addend_2)
            elif sign == '-':
                result = int(addend_1) - int(addend_2)
            result_row.append(' '*(row_length-len(str(result))) + str(result))

    # Unire gli elementi di ciascuna lista con quattro spazi e stampare le righe risultanti
    #print('    '.join(first_row))
    #print('    '.join(second_row))
    #print('    '.join(separator_row))
    #if show_answers:
    #    print('    '.join(result_row))

    #return problems
    output = '    '.join(first_row) + '\n'
    output += '    '.join(second_row) + '\n'
    output += '    '.join(separator_row)
    if show_answers:
        output += '\n' + '    '.join(result_row)

    return output


def contiene_alfabetici(s):
    for char in s:
        if char.isalpha():
            return True
    return False


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

As a matter of fact Iā€™ve added error handling and changed print() callings storing the result in the variable output. The result is still identical to solution, why donā€™t I get it correct?

Yes, actually it was my misreading that led me to miscomprehnsion of the task, thanks for the patience!

If you use repr() it will show the raw format identical to the test. Itā€™s easier to see trailing spaces and newlines this way:

print(repr(arithmetic_arranger(problems,True)))

these also need to be returned, everything needs to be returned

2 Likes

In order to do this Iā€™ve changed it into:

if (len(addend_1) > 4):
            output = "Error: Numbers cannot be more than four digits."
            break

and then at the end of the function I have:

return output

Then I call the function in this way (for example):

problems = ["3a2 + 698", "3801 - 2", "45 + 43", "123 + 49"]
print(arithmetic_arranger(problems,True))

Is it correct to do like that? So Iā€™m giving as return value of the function the output object, which will be an error message or the operations formatted and then this output is printed wheter is one of the two(actually more than only twoā€¦) cases.
Does it make sense?

Edit: as said in this comment it works when problems are correctly inserted, but now the error messages are not showed anymore and donā€™t understand whyā€¦ Iā€™m calling something like print(output) where output is a string, why should it not printing it on screen?

I take the time to really appreciate your effort in replying to me, Iā€™m quite new with Python and Iā€™m trying to learn the most.

Iā€™ve corrected the code, but I still donā€™t understand how to get the output without calling to print function.

Iā€™ve run this code:

def arithmetic_arranger(problems, show_answers=True):
    """problems is a list of strings"""
    first_row       = [] # implemento le righe come liste
    second_row      = []
    separator_row   = []
    result_row      = []
    counter         = 0  # contatore per il numero di problemi

    for pb in problems:
        addend_list = pb.split(' ')         # separo numeri e segno
        addend_1 = addend_list[0]  
        # checking addend_1 length
        if (len(addend_1) > 4):
            return "Error: Numbers cannot be more than four digits."
        if contiene_alfabetici(addend_1) == True:
            return "Error: Numbers must only contain digits"
        # checking correct operator insertion
        if (addend_list[1] == '*'):
            return "Error: Operator must be '+' or '-'."      
        if (addend_list[1] == '/'):
            return "Error: Operator must be '+' or '-'."      
        sign     = addend_list[1]
        addend_2 = addend_list[2]
        # checking addend_2 length
        if (len(addend_2) > 4):
            output ="Error: Numbers cannot be more than four digits."
            break
        if contiene_alfabetici(addend_2) == True:
            output = "Error: Numbers must only contain digits"
            break

        row_length = max(len(addend_list[0]),len(addend_list[2])) + 2       
        first_row.append(' '*(row_length-len(addend_list[0])) + addend_list[0])        #prima riga
        second_row.append(sign + ' '*(row_length-len(sign)-len(addend_2)) + addend_2)  #seconda riga
        separator_row.append('-'*row_length)                                           #riga separatrice

        if show_answers:          # controllo per visualizzazione risultato
            if sign == '+':
                result = int(addend_1) + int(addend_2)
            elif sign == '-':
                result = int(addend_1) - int(addend_2)
            result_row.append(' '*(row_length-len(str(result))) + str(result))
        counter += 1
        if counter > 4:
            return "Error: Too many problems."
        
    # Unire gli elementi di ciascuna lista con quattro spazi e stampare le righe risultanti
    output = '    '.join(first_row) + '\n'
    output += '    '.join(second_row) + '\n'
    output += '    '.join(separator_row)
    if show_answers:
        output += '\n' + '    '.join(result_row)

        
    return output


def contiene_alfabetici(s):
    for char in s:
        if char.isalpha():
            return True
    return False

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

And it does not print anything on screen, while if I change the last line of code into

print(arithmetic_arranger(problems,True))

it then works correctly :slight_smile:
Iā€™m really struggling in understanding how I can return those lines which contains the formatted operations without using the print function calling.

returning a value from a function and printing are two different things

you can do this to see what your function is returning, you are using print to capture the returned value from the function and show it in the terminal

Now that your function return the values, you can open the browser console (F12), when you run the tests, the failing tests will have extra output in the browser console you can use to see what issue your output is having

For examle

AssertionError: '\n\n\n' != 'Error: Numbers cannot be more than four digits.'

here the first string is the output of the function and the second string is the expected output. Your way of returning the errors is not working.

Remeber you can have multiple returns in a function if you want

1 Like

Iā€™ve run the tests and errors are valid; however I donā€™t understand why this

10. arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40"], True) should return    32         1      45      123      988\n- 698    - 3801    + 43    +  49    +  40\n-----    ------    ----    -----    -----\n -666     -3800      88      172     1028

have to occur. Is not the request to prevent the user from computing more than 4 problems? This is a 5-problem case, why the solution accept it although?

please read again the instructions, section ā€œSituations that will return an errorā€

1 Like

My fault, I apologize. I did not read properly, thank you! Now I get it correct :slight_smile:

Iā€™m now struggling with this, hope I wonā€™t be missing attention to the instructions for this:

arithmetic_arranger(["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"]) should return   11      3801      1      123         1\n+  4    - 2999    + 2    +  49    - 9380\n----    ------    ---    -----    ------

Iā€™ve checked spacings and sums, they are properly made and displayed as requested. Iā€™ve tried to open the browser console (F12) but it raises up to 113 issues and I do not know where to find more explanation. Are there any recurring error about this case I could think about to solve it?
Thank you in advance

Iā€™ve made it, I was leaving the flag as True, the system wanted to test the problems with the False case. Iā€™ve finished the excercise by doing so.
Thanks a lot for your time both pkdvalis and Ilenia :heart_eyes:

1 Like

Glad you got it! This is a bit late but hereā€™s a primer on reading the errors in the console.

The assertion error and diff gives you a lot of information to track down a problem. For example:

AssertionError: 'Year' != 'Years'
- Year
+ Years
?     +

Your output comes first, and the output that the test expects is second.

AssertionError: ā€˜Yearā€™ != ā€˜Yearsā€™

Your output: Year does not equal whatā€™s expected: Years

This is called a diff, and it shows you the differences between two files or blocks of code:

- Year
+ Years
?     +

- Dash indicates the incorrect output
+ Plus shows what it should be
? The Question mark line indicates the place of the character thatā€™s different between the two lines. Here a + is placed under the missing s .

Hereā€™s another example:

E       AssertionError: Expected different output when calling "arithmetic_arranger()" with ["3801 - 2", "123 + 49"]
E       assert '  3801      123    \n   - 2     + 49    \n------    -----    \n' == '  3801      123\n-    2    +  49\n------    -----'
E         -   3801      123
E         +   3801      123    
E         ?                ++++
E         - -    2    +  49
E         +    - 2     + 49    
E         - ------    -----
E         + ------    -----    
E         ?                +++++

The first line is long, and it helps to view it as 2 lines in fixed width characters, so you can compare it character by character:

'  3801      123    \n   - 2     + 49    \n------    -----    \n'
'  3801      123\n-    2    +  49\n------    -----'

Again, your output is first and the expected output is second. Here itā€™s easy to see extra spaces or \n characters.

E         -   3801      123
E         +   3801      123    
E         ?                ++++

Here the ? line indicates 4 extra spaces at the end of a line using four + symbols. Spaces are a little difficult to see this way, so itā€™s useful to use both formats together.

I hope this helps interpret your error!

1 Like

when you ask for help please open your own topic, but also please read again the section on when the function should return an error