Search code examples
pythonpython-3.xjustify

Not able to let justify the output in python


In one of the problems for Code Jam 2020, I am getting the below output

Case #1:    CJC
Case #2: IMPOSSIBLE
Case #3:      CJJCC
Case #4:   CC

Meanwhile, the real output should have been like this:

Case #1: CJC
Case #2: IMPOSSIBLE
Case #3: JCCJJ
Case #4: CC

Can anyone tell how to rectify this? I am using python 3. My print statement is like this: print('Case #{}: {}'.format(count, output))

Below is my code.

def checkOverlap(task1,task2):
start1 = int(task1[0])
start2 = int(task2[0])
end1 = int(task1[1])
end2 = int(task2[1])

if(end2 > start1 and start2 < end1):
    return True
else:
    return False


T= input()
test = int(T)
countTest = 0
while(countTest<test):
    A = input()
    countA = int(A)
    lim = 0
    activity = []
    while(lim<countA):
        activity.append(input().split(" "))
        lim += 1

    flag = True
    output=' '*countA
    output+='C'
    J=[]
    C=[activity[0]]

   impossible = False
   for i in range(0,countA-1):
       for j in range(i+1,countA):
           if (C.__contains__(activity[i]) and J.__contains__(activity[j])) or \
               (J.__contains__(activity[i]) and C.__contains__(activity[j])):
               continue

           check = checkOverlap(activity[i],activity[j])
           if(check == False):
               if C.__contains__(activity[i]):
                   if not C.__contains__(activity[j]):
                       C.append(activity[j])
               else:
                   if not J.__contains__(activity[j]):
                       J.append(activity[j])
           else:
               if (C.__contains__(activity[i])):
                   if(C.__contains__(activity[j])):
                    impossible = True
                   else:
                       if not J.__contains__(activity[j]):
                           J.append(activity[j])
               else:
                   if J.__contains__(activity[j]):
                       impossible = True
                   else:
                       if not C.__contains__(activity[j]):
                           C.append(activity[j])

   if impossible == True:

       output = 'IMPOSSIBLE'


   else:
       for i in range(1,countA):
           if C.__contains__(activity[i]):
               output += 'C'
           else:
               output += 'J'
   count = (countTest + 1)
   print('Case #{}: {}'.format(count, output))



   countTest += 1

Solution

  • Why is this line in your code?

        output=' '*countA
    

    If you get rid of it (switching to, say, output = ""), you'll be happier. What yours does is start the string off with a bunch of spaces, which later get printed. (Everything else you've added gets appended, so your final string will be "    CJJCC".) That messes with the alignment you wanted.