Search code examples
pythonformattingmultiplication

Python and CodeEval: Why isn't my solution to this Multiplication Table challenge not correct?


So I've been digging into some of the challenges at CodeEval during the last couple of days. One of them asks you to print a pretty-looking multiplication table going up to 12*12. While on my computer this solution works properly, the site does not accept it.

Can somebody help me out?

for i in range(1,13):
    for j in range(1,13):
       if j==1:
        print i*j,
       elif i>=10 and j==2:
        print '{0:3}'.format(i*j),
       else:
        print '{0:4}'.format(i*j),
    print 

Here's a description of the challenge:

Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).


Solution

  • Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).

    I think that following code may pass, according to the given rules. But it's only a guess as I'm not playing on codeeval.

    # python3 code, use from __future__ import print_function if you're using python2
    for i in range(1,13):
        for j in range(1,13):
            print('{:4}'.format(i*j), end="")
        print ("")
    

    I guess your problem is that you're having a 5 alignment because you forgot that the print foo, syntax in python 2 is adding a space. Also they say width of 4, whereas you tried to be smart, and align accordingly to the size of the value.

    edit: here's more details about what's wrong in your code, let's take two lines of your output:

    1    2    3    4    5    6    7    8    9   10   11   12
    10  20   30   40   50   60   70   80   90  100  110  120
    AA␣BBB␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣
    

    so what your code is doing is:

    if j==1: print i*j,
    

    outputs the AA␣,

    elif i>=10 and j==2:
        print '{0:3}'.format(i*j),
    

    outputs the BBB␣ and

    else:
        print '{0:4}'.format(i*j),
    

    outputs the CCCC␣.

    The is an extra space added by python because of the use of the , at the end of the print, to get that, see that snippet:

    >>> def foo():
    ...  print 1234,
    ...  print 1234,
    ...  print
    ... 
    >>> foo()
    1234 1234
    

    The format '{0:3}' right aligns the integer to the right as expected, but only with a padding of three, whereas the '{0:4}' does it according to the rules. But as you're adding an extra space at the end, it's not working as you're writing it. That's why it's better to use python3's print expression that makes it simpler, using the end keyword.