Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 841
Kunal Vyas Avatar asked Jun 07 '15 22:06

Kunal Vyas


2 Answers

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
like image 155
Bhargav Rao Avatar answered Oct 21 '22 23:10

Bhargav Rao


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.

like image 44
Utsav T Avatar answered Oct 21 '22 21:10

Utsav T