output same as expected output, but test fail!

Question asked is:

Read a string of length 15, read r and c integers such that r*c=15, arrange the elements of string in form of a matrix which has r rows and c columns.

sample input

goodprogrammer!

3

5

sample output:

g o o d p

r o g r a

m m e r !


My code :

s=str(input())

r=int(input())

c=int(input())

if len(s) != 15:

print('invalid input')

else:

if r*c != 15:

    print ('invalid input')

else:

    i=0

    for element in s:

        print(element,"",end="")

        i=i+1

        if i%c == 0:

            print()

My output is same as the sample output when I entered input same as sample input. but my code didnt pass. can anyone tell me what’s wrong?

Thanks!

Change the first else to elif r*c!=15:. The last else is not having any if associated with it.

Also is this code not giving syntax error?

I think it’s likely that the problem is extra spaces in your output. This will be hard to see just by looking at the output. There are various ways to overcome this, but within the structure you have, it might be best to form an output string per row rather than trying to print character by character.



For string input it’s often a good idea to remove any lurking whitespace using input().strip()

If you wanted a bit more general purpose code, you could just check
if r*c != len(s):
and ignore the requirement for exactly 15 characters. In fact, even with the 15 characters specified, I would substitute that test for one of the tests you make.

You could also combine the two validity tests of course with
if len(s) != 15 or r*c != 15:
(unless you wanted different error messages for different errors).

For extension, you might want to try turning input of

pythonprogrammer
5

(where I’m just getting columns, not rows) into

p y t h o
n p r o g
r a m m e
r

why would it give syntax error?