la flare la flare - 7 months ago 15
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
else:
break

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

insertionSort(a)
print(a)


This is what is in the file:

7686850495948548545


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

Answer

This part is not quite right.

infile = open("file1.txt", "r")
a=[]
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 = in_file.read()

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]

EDIT:

just for fun, here's the concise version:

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

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