0

Pythonでマージソートを実装しようとしています

#!/usr/bin/python
import math

def merge_sort(unsorted):
    if(len(unsorted)<2):
        return unsorted
    middle = int(math.floor(len(unsorted)/2))
    left = merge_sort(unsorted[0:middle])
    right = merge_sort(unsorted[middle:])
    return merge(left, right)

def merge(left, right):
    results = []
    while (len(left) > 0 and len(right) > 0 ):
        if(left[0] < right[0]):
            results.append(left.pop(0) )
        else:
            results.append( right.pop(0))

    if (len(left) > 0):
        results.append(left)
    if (len(right) > 0):
        results.append(right)

    return results

print merge_sort(list('7123'))

ただし、私の結果は[['1'], ['2'], ['3'], [['7']]]ではなく次のようになり['7', '1', '2', '3']ます。

私の構文のエラーは何ですか?

4

1 に答える 1

5

ここで使用list.extend:

if (len(left) > 0):
    results.extend(left)
if (len(right) > 0):
    results.extend(right)

list.appendlist.extend:

>>> lis = [1, 2 , 3]
>>> lis.append( [4, 5] )  #appends the whole object at the end of the list
>>> lis
[1, 2, 3, [4, 5]]
>>> lis.extend( [6, 7] )  #appends individual items from the iterable
>>> lis
[1, 2, 3, [4, 5], 6, 7]

ヘルプlist.extend:

>>> print list.extend.__doc__
L.extend(iterable) -- extend list by appending elements from the iterable
于 2013-05-21T07:50:33.123 に答える