Search code examples
pythonfunctionstring-formatting

printing formatted list items on the same line in python


I am a beginner programmer working through one of the final projects on freecodecamp.

I am using Mac OS python3.10

The problem requests that we create a funciton that takes a list of horizontally arranged arithmetic problems as an argument and rearranges them vertically.

This is the function call:

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

And this is the desired outcome:

   32      3801      45      123
+ 698    -    2    + 43    +  49
-----    ------    ----    -----

I was able to reformat the equations vertically but I got stuck trying to figure out how to print them side by side on the same line. Here is the code I wrote.

def aa(problem) :
    for i in problem[:] :
        problem.remove(i)
        p = i.split()
        # print(p)
        ve = '\t{:>5}\n\t{:<1}{:>4}\n\t-----'.format(p[0],p[1],p[2])
        print(ve)

    return

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

And here is the outcome of that code.

   32
+ 698
-----
 3801
-   2
-----
   45
+  43
-----
  123
+  49
-----

I have already tried using print(*variable) and ' '.join. When i try those solutions I get this.

       3 2
 +   6 9 8
 - - - - -
   3 8 0 1
 -       2
 - - - - -
       4 5
 +     4 3
 - - - - -
     1 2 3
 +     4 9
 - - - - -

I appreciate you taking the time to read my problem, and thanks for the help.


Solution

  • Here's a solution that exactly matches the desired outcome. It determines the widths of each equation:

    def arithmetic_arranger(equations):
        # Parse to list of lists, e.g.:
        #   [['32', '+', '698'], ['3801', '-', '2'], ['45', '+', '43'], ['123', '+', '49']]
        parsed = [equation.split() for equation in equations]
    
        # For each sublist, determine the widest string and build a list of those widths, e.g.:
        #   [3, 4, 2, 3]
        widths = [len(max(items,key=len)) for items in parsed]
    
        # zip() matches each width with each parsed sublist.
        # Print the first operands right-justified with appropriate widths.
        print('   '.join([f'  {a:>{w}}' for w,(a,op,b) in zip(widths,parsed)]))
    
        # Print the operator and the second operand.
        print('   '.join([f'{op} {b:>{w}}' for w,(a,op,b) in zip(widths,parsed)]))
    
        # Print the dashed lines under each equation.
        print('   '.join(['-'*(w+2) for w in widths]))
    
    arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])
    

    Output:

       32     3801     45     123
    + 698   -    2   + 43   +  49
    -----   ------   ----   -----