简体   繁体   中英

Trouble using insertion sort with a Python list

I'm given a text file that resembles the following...

hello 20
world 30
i'm 50
ok 20

I'm trying to use insertion sort to arrange the numerical part of the data. My code looks like the following...

def insertion_sort():
    filename = input('Enter filename: ')
    lst = []
    for line in open(filename):
        lst.append(int(line))
    print(lst)
    for index in range(1,len(lst)):
        value = lst[index]
        leftvalue = index -1
        while leftvalue >= 0 and lst[leftvalue] > value:
            if value < lst[leftvalue]:
                lst[leftvalue + 1] = lst[leftvalue]
                lst[leftvalue] = value
                leftvalue = leftvalue - 1
            else:
                break
    return lst == insertion_sort()

I'm getting the following error... ValueError: invalid literal for int() with base 10: 'Merchant_0 96918\\n'

I have tried using float in replacement with int but I can't convert strings to floats.

You can't get an integer with :

lst.append(int(line))

if line contains, say 'world 30'

What do you try to obtain exactly ? If you want to get the numeric value, try :

int(line.split(' ')[1])

Or better (works even if there are multiple spaces in the input lines) :

import re
reobj=re.search('(\d+)$',line)
int(reobj.group(1))

The whole sorting process becomes :

import operator
import re

lines = {}
for line in open('tst.txt'):
    reobj=re.search('(\d+)$',line)
    int_key=int(reobj.group(1))
    value=line[0:reobj.start()]
    lines[int_key]=value

# See : http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value?rq=1
print "Sorted : ", sorted(lines.iteritems(), key=operator.itemgetter(0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM