1

So I've got a .txt file as follows:

131,263.07
47,170.14
170,190.01
180,412.69
53,401.53

And I had to read the file so as to output the list like:

131 kms, $263.07
47 kms, $170.14
170 kms, $190.01
180 kms, $412.69
53 kms, $401.53

The code I used was:

def PrintList(table):
    for line in table:
       print(str(line[0]) + " kms, $" + str(line[1]))

file = open(input("Enter file name: ")) 

table = []
for line in file:
    line = line.rstrip().split(",")
    line[0] = int(line[0])
    line[1] = float(line[1])
    table.append(line)

PrintList(table)

file.close()

And now I'd like to sort the list in increasing order of price to obtain:

47 kms, $170.14
170 kms, $190.01
131 kms, $263.07
53 kms, $401.53
180 kms, $412.69

How would I implement this in Python? I've tried doing this using Selection Sort but it just doesn't seem to be working.

Update: Thanks for the input so far. However, I have tried the sort function but I'd like to figure out how to implement this using Selection Sort.

Update: I am unable to post the Selection Sort code that I have used as I have overwritten it, nonetheless given below is an example of the code (which I have used to sort a random list of distances) which I had to modify to sort the aforementioned list in increasing order of price. Hope it's sufficient.

def selectionSort(distance):
    n = len(distance)
    for i in range(n):
        minPlace = searchMin(distance)
        swap(distance, i, minPlace+i)

def searchMin(distance):
    minPlace = 0
    n = len(distance)
    for i in range(1, n):
        if distance[i] < distance[minPlace]:
            minPlace = i
        return minPlace

def swap(distance, i, j):
    temp = distance[i]
    distance[i] = distance[j]
    distance[j] = temp

If there's an easier way to implement this, please let me know. Thanks in advance. Cheers.

5
  • have you used the sort function? Commented May 5, 2016 at 16:37
  • Yes, I have. However, I'd like to figure out how to implement it using Selection Sort. Commented May 5, 2016 at 16:48
  • all the answers you are getting are about "here is how to get python to sort it for you" but do you want help with your sorting algorithm that didn't work? Commented May 5, 2016 at 16:52
  • 1
    can you show your code so far and what's not working. Commented May 5, 2016 at 16:53
  • ^ the code for the selection sort you tried. Commented May 5, 2016 at 16:54

4 Answers 4

1

Python lists come with a sort method already. You can simply call it, specifying a key argument to determine how to sort.

def print_list(table):
    for line in table:
       print(str(line[0]) + " kms, $" + str(line[1]))

with open(input("Enter file name: ")) as f:
    table = []
    for line in f:
        line = line.rstrip().split(",")
        line[0] = int(line[0])
        line[1] = float(line[1])
        table.append(line)

    table.sort(key=lambda line: line[1])
    print_list(table)

Note that I made a couple of additional changes to your program, namely renaming PrintList in accordance with PEP8, and using the with statement so that the file gets closed automatically.

If insist on using Selection Sort (it will be worse than Python's default sorting), implement it in a helper function that fulfills the interface of sorted.

Sign up to request clarification or add additional context in comments.

2 Comments

you may want to link to the specific section of PEP 8 for function naming conventions.
@TadhgMcDonald-Jensen Thanks for the hint! Edited. In the future, feel free to edit my posts if you're clarifying links. Have a nice day!
0

Is it absolutely necessary to implement selection sort? I would go with sorted:

PrintList(sorted(table, key = lambda x: x[1]))

where

key = lambda x: x[1]

instructs sorted to use the value of the element with index 1 (price) to compare your objects.

1 Comment

Yeah, I'd like to see how it works with Selection Sort.
0

after your for-loop:

sorted_table = sorted(table, key=lambda row: row[1], reverse=True)

Sorted_table now contains your tabular data, sorted by the 2nd column. You can then pass sorted_table to your PrintList function. An alternative that avoids the lambda:

from operator import itemgetter
sorted_table = sorted(table, key=itemgetter(1), reverse=True)

For more on python sorting, see: https://wiki.python.org/moin/HowTo/Sorting

2 Comments

I think that adding reverse=True would sort the list in descending order.
You can use list.sort() to sort in place instead of creating a new list.
0

Brute force selection sort

lst = [56,2,5,3,6,4,7,1,8,10,34]
print(lst)

#Total length of the list
leng=len(lst)

#Loop from 1st to last of the list
for i in range(leng):
    #Assume first value as minimum 
    min = lst[i]
    print(min,'Minimum value before the for loop')
    #Scan through every value for checking the minimum 
    for j in range(i,leng):
        if lst[j] < min:          
            min=lst[j]
            ts=j
            print(min,"Minimum value", ts, "Is it's corresponding index")
    #We have now the new minimum value and it's corresponding index.
    #Swap the new minimum value and the corresponding index            
    if min <lst[i]:
         temp =lst[i]
         lst[i]=lst[ts]   
         lst[ts]=temp
    print(lst,'Outer list')

1 Comment

You've labeled your example as „Brute force selection sort“ SudheeM. The fact you made such a distinction suggests that there are other alternatives. Even if you don't point out why the distinction is important, it would be helpful to a lot of us if you amended your answer with a brief note saying why you went for this particular approach and not some other non brute force alternative. TIA.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.