Kunal Vyas
Kunal Vyas

Reputation: 1579

Print list elements on new line

I wish to print the elements of an array, without commas, and on separate lines. I am writing a function for insertion sort. Though it works correctly, I am finding it tricky to print them properly. The code I've written is:

#!/bin/python
def insertionSort(ar):    
    newNo = ar[-1]
    for i in range(0, m-1):
        if(newNo < ar[m-i-1]):
            ar[m-i] = ar[m-i-1]
            for e in ar:
                print e,
            print '\n'
    ar[m-i-1] = newNo
    for f in ar: print f,

m = input()
ar = [int(i) for i in raw_input().strip().split()]
insertionSort(ar)

The output I get is:

2 4 6 8 8 

2 4 6 6 8 

2 4 4 6 8 

2 3 4 6 8

I should get the following output for the code to pass the test case:

2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 3 4 6 8

i.e without the extra space between lines. Click here for the detailed problem statement.

Upvotes: 6

Views: 2189

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52071

print statement appends a new line automatically, so if you use

print '\n'

You will get two new lines. So you can use an empty string as in print '' or the better way would be to use print by itself :

print

Upvotes: 5

Utsav T
Utsav T

Reputation: 1545

This could be a fix -

def insertionSort(ar):    
newNo = ar[-1]
for i in range(0, m-1):
    if(newNo < ar[m-i-1]):
        ar[m-i] = ar[m-i-1]
        for e in ar:
            print e,
        print 
ar[m-i-1] = newNo
for f in ar: print f,

m = input()
ar = [int(i) for i in raw_input().strip().split()]
insertionSort(ar)

Edit - Ok ! ^ Someone already mentioned that.

Upvotes: 1

Related Questions