la flare la flare - 5 months ago 6
Python Question

Sort a list read from a file?

def insertionSort(a):
for i in range(1, len(a)): #outer loop covering the range
value = a[i] #value = to list, which will compare items to the left
i = i - 1 #i goes lower than index to compare further to the left
while i >= 0 : #keep comparing till its at the beginning of the list
if value < a[i]: #if value is less than i
a[i+1] = a[i] # shift number in right i to slot i + 1
a[i] = value # shift value that was left into slot i
i = i - 1

infile = open("file1.txt", "r")
for aline in infile:
a = aline.split()


This is what is in the file:


How do I get the
function to work on a file?


This part is not quite right.

infile = open("file1.txt", "r")
for aline in infile:
    a = aline.split()

The preferred way of opening and reading(or writing) a file is the following:

with open('some_file.txt', 'r') as in_file:
  string_numbers =

Then, once you have the numbers in a string, you can split them into a list like so:

nums_list = list(string_nums)

So nums_list is now a list of string, convert them to ints with list comprehension:

nums = [int(num) for num in nums_list]


just for fun, here's the concise version:

with open('filename.txt') as in_file:
  nums = [int(n) for n in list(]

.strip() added just to ensure no strange whitespace casting.