0

I am a python newbie so am writing small programs to get more familiar. I have a rasp PI to, very unix skilled,done programming but not python3. One of these is a simple bubble sort, it reads in two txt files with numbers 5 9 2 19 18 17 13 and another with different numbers 10 14 2 4 6 20 type thing

I use a function to read in each file then join them before I bubblesort the whole string, I'm aware it needs to be a list so that the bubblesort function can move the numbers around during each pass. From what I can tell my issue is the mergesort (var name for the concatenated list) always is a string.

Anyone shed any light on why this is so? and how could I convert the two files into a single list? ------------------sample code-------------------

mergesort = []

def readfile1():
    tempfile1 = open('sortfile1.txt','r')
    tempfile1 = tempfile1.read()
    return tempfile1


def readfile2():
    tempfile2 = open('sortfile2.txt','r')
    tempfile2 = tempfile2.read()
    return tempfile2

sortstring1 = readfile1()
# print (sortstring1)

sortstring2 = readfile2()
# print (sortstring2)

# mergesort = list(set(sortstring1) | set(sortstring2)
mergesort = sortstring1 + sortstring2
print (mergesort, "Type=", type(mergesort))

1 Answers1

0

Assuming you want to get one list of integers, you could do it like this. Notice I also combined your functions into one because they were doing the exact same thing.

In your code, you are not splitting the contents of the file into a list, so it was read in as a string. use the split() method to split a string into a list.

def read_file_to_list(filename):
    temp = open(filename, 'r')
    string = temp.read()
    numbers = [int(x) for x in string.split(' ')]
    return numbers

sort1 = read_file_to_list('sortfile1.txt')
sort2 = read_file_to_list('sortfile2.txt')

total = sort1 + sort2
Brobin
  • 3,241
  • 2
  • 19
  • 35
  • Thank you Sir, I had thought about combining the two file reads but had not thought about reads going into a string, so your example was of great use from my learning perspective. – Mrhamster99 Mar 14 '15 at 21:09
  • Thank You Sir - Excellent lesson in file reads,strings and functions, bubble sort works a treat which in itself was a great learning opportunity. – Mrhamster99 Mar 14 '15 at 21:11
  • Now I would suggest you look into merge and quick sort. They are much more efficient and pretty fun and easy to learn in python – Brobin Mar 14 '15 at 21:36