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.