2

I'm doing the merge sort in python but I have a problem. When I try to insert the list from the console (one number per line which return a list of string) I cannot convert it in integers. Can you help me understanding the problem.

import sys

def mergeSort(lista):
    res = []
    for i in lista[0].split():
        res.append(int(i))
    if len(res)>1:
        mid = len(res)//2
        lefthalf = res[:mid]
        righthalf = res[mid:]
        mergeSort(lefthalf)
        mergeSort(righthalf)
        i=0
        j=0
        k=0
        while i<len(lefthalf) and j<len(righthalf):
            if lefthalf[i]<righthalf[j]:
                res[k]=lefthalf[i]
                i=i+1
            else:
                res[k]=righthalf[j]
                j=j+1
            k=k+1

        while i<len(lefthalf):
            res[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j<len(righthalf):
            res[k]=righthalf[j]
            j=j+1
            k=k+1
    print(res)

alist = []
for l in sys.stdin:
    alist.append(l.strip())
mergeSort(alist)

The code error says: AttributeError: 'int' object has no attribute 'split' The input is a file (given from the shell with the command: "python3 merge.py < data.txt") with the list of numbers one per line. Example: 2 3 0 12 11 7 4 Should return 0 2 3 4 7 11 12 Of course I don't have an output because of the error

7
  • 1
    All this means is the first item in lista is an int object, not a string. Somehow your code is is appending an integer to the list you're passing in. So this can't be a complete code example... Commented Feb 27, 2015 at 16:39
  • but they are all one unit string... Commented Feb 27, 2015 at 16:43
  • The only place your code shows that uses str.split() is on an element of a list that ostensibly contains strings. You're probably not looking at the same code you're running, or you didn't post the same code you're running here. Commented Feb 27, 2015 at 16:46
  • 1
    I can swear the code is the same. When I try to output the "lista", it returns: '1\r3\r4\r56\r65\r3\r4\r3\r2\r9\r10' Commented Feb 27, 2015 at 16:47
  • I see now on closer inspection. When you call mergeSort recursively you're passing in a list of integers rather than a list of strings. You should handle the conversion from strings to integers outside the mergeSort routine. Commented Feb 27, 2015 at 16:51

5 Answers 5

2

If you also want the index, you can use enumerate:

data = ['itemA', 'itemB', 'itemC', 'itemD']
for (i, item) in enumerate(data):
    print("Item #%d is %s" % (i, str(item)))

For future reference, you can debug like so:

def mergeSort(lista):
    res = []
    print(lista)
    for i in lista[0].split():
        print(i)
        res.append(int(i))
Sign up to request clarification or add additional context in comments.

2 Comments

Add the print statements to see the contents of the variable lista before the loop starts, and the contents of i at the beginning of each iteration -- they might not be what you expect.
And indeed it was not the output I was looking for. The output of the lista is '1\r3\r4\r56\r65\r3\r4\r3\r2\r9\r10' (That's why I was using split) and I cannot output 'i' because of the error in the loop
1

You're converting a list of strings to a list of integers at the top of your mergeSort routine. The subsequent recursive calls to mergeSort are trying to do the same, except now to lists of integers.

You should handle all file parsing completely separate from your mergeSort routine which should be designed just to work on a list of numbers. This is a "separation of concerns".

2 Comments

Absolutely right. I did the correction. Should I have to put the corrected code upstair?
If you wish. It might be better for future readers to see both versions, or least the relevant updates (not necessarily two full versions of the code since the merge sort details don't matter).
1

It should be for i in lista rather than for i in lista[0].split(), and you can simply achieve it by list comprehension: res = [int(num) for num in lista]

4 Comments

I already do it and I receive the error: invalid literal for int() with base 10: '1\r3\r4\r56\r65\r3\r4\r3\r2\r9\r10'
That's why I did split
@user28011994 Are you sure in your data.txt is one number per line? Looks like your alist contains only 1 element with all the numbers in it, which is weird.
I wrote it as 1 number per line
0

You're running this code in Python 2 and you only entered a single number. If that's true, replace input with raw_input and it should work.

Comments

-1

AttributeError: 'int' object has no attribute 'split' Can anyone help me with this

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.