4

I want to Bubblesort a file by numbers and I have propably 2 mistakes in my code.

The lines of the file contain: string-space-number

The response is a wrong sorting or sometimes I got also an IndexError because x.append(row[l]) is out of range

Hope someone can help me

Code:

#!/usr/bin/python
filename = "Numberfile.txt"
fo = open(filename, "r")

x, y, z, b = [], [], [], []

for line in fo:             # read
   row = line.split(" ")    # split items by space
   x.append(row[1])         # number


liste = fo.readlines()
lines = len(liste)
fo.close()

for passesLeft in range(lines-1, 0, -1):
    for i in range(passesLeft):
        if x[i] > x[i+1]:
                temp = liste[i]
                liste[i] = liste[i+1]
                liste[i+1] = temp

fo = open(filename, "w")
for i in liste:
    fo.writelines("%s" % i)
fo.close()

2 Answers 2

1

Seems that you have empty lines in the file.

Change:

for line in fo:             # read
   row = line.split(" ")    # split items by space
   x.append(row[1])         # number

with:

for line in fo:             # read
   if line.strip():
       row = line.split(" ")    # split items by space
       x.append(row[1])         # number

By the way, you're better off using re.split with the regex \s+:

re.split(r'\s+', line)

which will make your code more resilient - it will be able to handle multiple spaces as well.

For the second issue Anand proceeded me: you're comparing strings, if you want to compare numbers you'll have to wrap it with a call to int()

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

1 Comment

@SadCroco after you run into it many times (and hammer your head against the wall like I did each time...) - you'll finally get it ;)
1

First issue, if you are sorting based on the numbers and the numbers can be multiple digits, then your logic would not work because x is a list of strings , not integers, and when comparing strings, it compares lexicographically, that is '12' is less than 2 , etc. You should convert the number to int before appending to x list.

Also if you are getting ListIndex error, you may have empty lines or lines without 2 elements, you should correctly check you input, also you can add a condition to ignore the empty lines.

Code -

for line in fo:
   if line.strip():
       row = line.split(" ")
       x.append(int(row[1]))  

Comments

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.