-1

I am presently finishing a course in python and I came across this glitch which has stumped me for a few days. The result should resemble this:

   32      3801      45     123
+ 698    -    2    + 43    + 49    
  ---      ----      --     ---    
  730      3799      88     172  

However, it instead prints out this:

   32      3801      45     123
+ 698    -    2    + 43    + 49    
  ---      ----      --      --    
  730      3799      88     172  

Please notice the sum of dashes in the fourth equation. In the correct version, the number of dashes correlates to the length of the max number. However, in the incorrect version (my version) the number of dashes is 2 when the length of the max number is 3.

Here is the entire code

equations = ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]

def arithmetic_equation(arr):

    stepOne = ''
    stepTwo = ''
    stepThree = ''
    stepFour = ''

    finalLine = ''
    anotherLine = ''
    thirdLine = ''
    fourthLine = ''

    space = 4

    for item in equations:

        parts = item.split()

        x = parts[0]
        y = parts[2]
        c = parts[1]

        if c == '+': z = (int(x) + int(y)) 
        else: z = (int(x) - int(y))

        n = len(x) if (x > y) else len(y)


        stepOne = x.rjust(n + 2)
        stepTwo = c + ' ' + y.rjust(n)
        stepThree = '  ' + '-' * n
        stepFour = str(z).rjust(n + 2)

        finalLine += str(stepOne) + ' ' * space
        anotherLine += str(stepTwo) + ' ' * space
        thirdLine += str(stepThree) + ' ' * space    
        fourthLine += stepFour + ' ' * space


    print(finalLine.rstrip() + '\n' + anotherLine + '\n' + thirdLine + '\n' + fourthLine)

arithmetic_equation(equations)
mage76
  • 1
  • 2
    You're comparing the strings `"123" < "49"`, which evaluates to false. Try `n = max(len(x), len(y))`. – ddejohn Oct 22 '21 at 02:34
  • 1
    Please review [MCVE] guidance on posting code - there is no need to post so much data and code to just say "I need to show as many dashes as max number of digits in two numbers, sample data :123, 49 leads to '--' with couple lines of code showing inline values of 123, 49 and code just that produces '--'". – Alexei Levenkov Oct 22 '21 at 02:48
  • `n = len(x) if (x > y) else len(y)` This is the part of the code that is supposed to tell you how many `-` symbols to use, right? Hint: if you can meaningfully use `len` to measure `x` and `y`, are they strings, or integers? What happens if you compare the strings `'123'` and `'49'` - which is "larger"? Why? – Karl Knechtel Oct 22 '21 at 03:10

2 Answers2

0

just a minor change - you'll know why this works.

instead of

n = len(x) if (x > y) else len(y)

use

n = len(x) if len(x) > len(y) else len(y)
0

In the line n = len(x) if (x > y) else len(y) you forgot to add len() while comparing if x > y.

Try this:

n = len(x) if (len(x) > len(y)) else len(y)

Or better use this:

n = max(len(y), len(x))
Shwetha
  • 106
  • 8